Below code is dealing with a TYPE* const
pointer.
struct D {
void Check ()
{
D* const p = new D; // 2nd test is "p = 0;"
cout<<"p = "<<p<<endl;
(D*&)p = new D;
cout<<"p = "<<p<<endl; // prints 0, "p = 0;" at declaration
}
};
int main ()
{
D o;
o.Check();
}
My questions are,
- If you initialize with
0
, then even though typecasting next time will not work. Is doing such typecasting is undefined behavior ? this
pointer is also ofTYPE* const
type, then why compiler doesn't allow the same operation forthis
?
As others have said, this is undefined behaviour since it attempts to modify a
const
object. If you initialise it with zero then the compiler might treat it as a compile-time constant, and ignore any attempt to modify it. Or it might do something entirely different.this
is not an ordinary variable of typeTYPE * const
; it is an rvalue expression of typeTYPE *
. This means that it cannot be used as the target of an assignment expression, or bound to a non-constant reference, at all.This declaration says that
p
is a pointer toD
that is constant, that is it will never, ever change. It is always 0.Here you display the value of p, which you earlier said would always be 0. Guess why a 0 is displayed!
Yes.
It invokes undefined behavior, as it tries to change the const pointer.
Recall that
D* const p
declares a variablep
which is aconst
pointer to non-constD
.