Re: What is wrong with this reference?
Michael wrote:
This is the sample program:
#include<cstdio>
int main()
{
int*const a=new int;
const int*const&b=a;
printf("%p %p\n",&a,&b);
delete a;
return 0;
}
When running, it produces:
0x7fff1dc49fc8 0x7fff1dc49fb8
You sound surprised. A reference is initialised with an rvalue obtained
apparently from copying the original ('a'). So, it refers to some other
object, a temporary.
That means the memory locations of a and b are different i.e. a and b is
different object!
Yes.
> I want to make something that *a is modifiable but *b is
not (to be used inside a class) but the following code generates a
compile-time error:
#include<cstdio>
int main()
{
int*a=new int;
const int*&b=a;
printf("%p %p\n",&a,&b);
delete a;
return 0;
}
test.cpp:6: error: invalid initialization of reference of type ???const int*&???
from expression of type ???int*???
I am not sure why this is, to be honest with you. Those indirect const
qualifiers always confuse me.
The following code runs perfect:
Define "perfect", please.
#include<cstdio>
int main()
{
int a=new int;
Huh? What language is that? Java? This should be a compilation error.
const int&b=a;
printf("%p %p\n",&a,&b);
return 0;
}
What is the problem in the first code (I am using g++ 4.2.4)?
Problem? I don't see any problem.
struct A { int a; };
int main() {
A* pNormalA = new A;
pNormalA->a = 42; // hey, it's modifiable
A const* pConstA = pNormalA;
pConstA->a = 666; // error, not modifiable
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask