int main()
{
const int ia = 10;
int *pia = const_cast<int*>(&ia);
*pia = 5;
std::cout << &ia << "\t" << pia <<endl;
std::cout << ia << "\t" << *pia <<endl;
return 0;
}
输出是:
0x28fef4 0x28fef4
10 5
*pia
和ia
具有相同的地址,但它们具有不同的值。我的目的是用const_cast
修改一个常量值,结果显示不行。
有人知道为什么吗?
你看到 10
为 ia
打印的原因很可能是编译器优化:它看到一个 const
对象,决定它不是将要更改,并将最后的打印输出替换为:
cout<< 10 <<" "<<*ppa<<endl;
换句话说,生成的代码具有 const
的值“烘焙到”二进制文件中。
丢弃最初声明为 const
的对象的常量性并写入该对象是未定义的行为:
$5.2.11/7 - Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier68) may produce undefined behavior (7.1.5.1).
根据平台的不同,const
对象可能会被放置在一个 protected 内存区域中,您不能对其进行写入。解决类型系统中的 const
特性可能有助于您的程序编译,但您可能会看到随机结果甚至崩溃。