What is wrong with this reference?

M

Michael

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! 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*’

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;
}

What is the problem in the first code (I am using g++ 4.2.4)?
 
T

Triple-DES

What was wrong with the answers you received the first time you posted?

He corrected:
int a=new int;
to
int*a=new int;

I still have a hard time believing that this program "runs perfect",
given the line:
const int&b=a;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top