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)
我的问题是,
0
,那么即使下次类型转换不起作用.做这种类型转换是不确定的行为?this
指针也是TYPE* const
类型,那么为什么编译器不允许相同的操作this
?做这种类型转换是不确定的行为?
是.
(D*&)p = new D;
Run Code Online (Sandbox Code Playgroud)
它调用未定义的行为,因为它试图更改const指针.
回想一下,D* const p
声明一个变量p
,它是一个const
指向非const 的指针D
.