为什么"TYPE*const"指针的行为不同?

iam*_*ind 1 c++ pointers const this undefined-behavior

下面的代码是处理TYPE* const指针.

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();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,

  1. 如果你初始化0,那么即使下次类型转换不起作用.做这种类型转换是不确定的行为?
  2. this指针也是TYPE* const类型,那么为什么编译器不允许相同的操作this

Naw*_*waz 5

做这种类型转换是不确定的行为?

是.

(D*&)p = new D;
Run Code Online (Sandbox Code Playgroud)

它调用未定义的行为,因为它试图更改const指针.

回想一下,D* const p声明一个变量p,它是一个const指向非const 的指针D.