In article <Pi******************************@speyburn.esat.ku leuven.ac.be>, Xiaobin Yang wrote:
Have a look at the following code:
#include<iostream>
using namespace std;
int main()
{
const int a = 1;
const int* const aptr1 = &a;
int* const aptr2 = const_cast<int*>aptr1);
*aptr2 = 2;
cout<<a<<endl;
cout<<*(&a)<<endl;
cout<<*aptr1<<endl;
cout<<*aptr2<<endl;
}
Output is (for g++ (ver. 3.2) and visual C++ 6 compiler)
1
1
2
2
If ( aptr1 == &a ), how is it possible that " *aptr != *(&a)" ?
confusing....
a is declared as a const int. This means to the compiler that the value
of a can never change. Knowing that, the compiler just sends the value
1 to cout when it finds a or *(&a).
Exchanging the cout << X << endl whith printf("%d\n", X), g++ 3.3.3
emits:
movl $1, 4(%esp)
movl $.LC0, (%esp)
call printf
for the first calls to printf. Which says: Put the value 1 on the
stack; put the value .LC0 (.LC0 is a pointer to "%d\n") on the stack;
call printf.
const int a = 1;
generates
movl $1, -4(%ebp)
put the value 1 in memory located by -4(%ebp)
const int* const aptr1 = &a;
generates
leal -4(%ebp), %eax
load the effective address of -4(%ebp) (== &a) into %eax
movl %eax, -8(%ebp)
move the contents of %eax into memory -8(%ebp) (==aptr1)
int* const aptr2 = const_cast<int*>(aptr1);
generates
movl -8(%ebp), %eax
move the value of -8(%ebp) (==aptr1) int %eax
movl %eax, -12(%ebp)
move the value of %eax into memory -12(%ebp) (==aptr2)
*aptr2 = 2
generates
movl -12(%ebp), %eax
move the value of -12(%ebp) (==aptr2) into %eax
movl $2, (%eax)
put the value 2 into the address %eax points to (==*aptr2)
Now the value of the object a is 2, but the compiler nevertheless uses
the value 1 when it finds a in the source code. Lesson: casting away
constness doesn't always work.
--
Robert Bauck Hamar