Phlip posted:
Let me try to explain the illegality.
(int*) in C is the same as reinterpret_cast<> in C++.
Not really. "reinterpret_cast" can't cast pointers to functions if I recall
correctly, while C-style casts can.
C++ only defines
the result of such a cast if it casts a pointer to what the data really
is.
Such typecasts make the compiler pretend that a class A is an int. This
would be legal:
A * p = (A *)(int *) &x; // both could use reinterpret_cast
I don't think this should work. The two types, "A*" and "int*" are
unrelated. Yes, they are both pointers, but what they point to are totally
different. In three steps, here's what you're doing:
1: Start off with the expression "&x" which is of type "A*".
2: You then use a C-style cast to turn it into an "int*". The Standard
doesn't guarantee that an "int*" can reliably hold the address of an object
of type "A", so the value might get corrupted.
3: Now you use a C-style cast again to turn it into an "A*", but the value
may already have been corrupted.
It's quite like the following:
double k = 32.2342;
double f = (double) (int) k;
f will have the value of 32 rather than 32.2342.
Your code might do anything (including appear to work correctly)
because you don't know if the address of A::a is the same as the
address of its A. So your cast might not end up pointing to an int.
I believe this is true.
-Tomás