C++ – Why Different Behavior for TYPE* const Pointers?

c++constantspointersthisundefined-behavior

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,

  1. If you initialize with 0, then even though typecasting next time will not work. Is doing such typecasting is undefined behavior ?
  2. this pointer is also of TYPE* const type, then why compiler doesn't allow the same operation for this?

Best Answer

Is doing such typecasting is undefined behavior ?

Yes.

(D*&)p = new D;

It invokes undefined behavior, as it tries to change the const pointer.

Recall that D* const p declares a variable p which is a const pointer to non-const D.

Related Question