<分区>
我有以下代码:
const int k=1;
int *p=const_cast<int *>( &k);
cout<<"k before="<<*p<<endl;
*p=10;
*const_cast<int *>( &k)=12;
cout<<"k after="<<k<<endl;
输出是:
k before=1
k after=1
为什么 const cast 在这里不起作用?
标签 c++ const-cast
<分区>
我有以下代码:
const int k=1;
int *p=const_cast<int *>( &k);
cout<<"k before="<<*p<<endl;
*p=10;
*const_cast<int *>( &k)=12;
cout<<"k after="<<k<<endl;
输出是:
k before=1
k after=1
为什么 const cast 在这里不起作用?
最佳答案
const_cast
导致 undefined behaviour 如果你放弃 const
然后写入值。正如您在此处看到的,什么都不做是有效的行为。
在您的特定示例中,可能发生的情况是编译器看到 k
是使用 const
存储类声明的,知道它不能(合法)改变和替换
cout<<"k after="<<k<<endl;
与
cout<<"k after="<<1<<endl;
如果您关闭优化,您可能(或可能不会)得到不同的结果。
放弃 const
调用未定义行为的真正原因是编译器可以自由地进行这样的优化。如果 const
变量可以自由地转换为非 const
变量并写入,那么 const
对编译器来说绝对没有意义。
关于c++ - const_cast 不适用于 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8954260/