Why different behavior for “TYPE* const” pointers?

倖福魔咒の 提交于 2019-12-20 04:49:46

问题


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?

回答1:


  1. 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.

  2. this is not an ordinary variable of type TYPE * const; it is an rvalue expression of type TYPE *. This means that it cannot be used as the target of an assignment expression, or bound to a non-constant reference, at all.




回答2:


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.




回答3:


D* const p = 0;

This declaration says that p is a pointer to D that is constant, that is it will never, ever change. It is always 0.

cout<<"p = "<<p<<endl;

Here you display the value of p, which you earlier said would always be 0. Guess why a 0 is displayed!



来源:https://stackoverflow.com/questions/5659157/why-different-behavior-for-type-const-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!