Re: What is wrong with this reference?
On Jan 29, 2:31 pm, Michael <mich...@michaeldadmum.no-ip.org> 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
That means the memory locations of a and b are different i.e.
a and b is different object!
Obviously. The have different types (int* and int const*). One
object can never have two different types.
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 \u2018cons=
t int*&\u2019
from expression of type \u2018int*\u2019
Consider the following:
int const a = 43 ;
int const* pa = &a ;
int* b ;
int const*& rb = b ; // This is what the compiler is
// complaining about
rb = pa ;
*b = 0 ;
If const is to mean anything, one of the last three statements
above must be illegal. And it's hard to imagine how to make the
last two illegal, so the conversion in the third from the bottom
is banned.
The following code runs perfect:
#include<cstdio>
int main()
{
int a=new int;
const int&b=a;
printf("%p %p\n",&a,&b);
return 0;
}
I can't get it to compile. Are you sure about the initializer
of a?
With an initializer of type int, there's nothing wrong with it.
A reference to an int const can refer to an int that isn't
const, just as a pointer to an int const can refer to an int
that isn't const. It's when you start adding levels of
indirection that it stops working. A pointer or a reference to
a cv-qualified type can refer to anything of that type whose
cv-qualifications are less than or equal to those of the pointer
or reference. Thus, a reference to an int* const can refer to
an int*. But not to an int const*; the types (and not just the
cv-qualifiers) of the pointer are different.
What is the problem in the first code (I am using g++ 4.2.4)?
Nothing. You initialized a reference with an rvalue, which
creates a temporary, and binds the reference to that temporary.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34