我们可以使用const_cast修改常量吗? [英] Can we use `const_cast` to modify a constant variable?
问题描述
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
修改一个常量值,但结果表明它不起作用。
*pia
and ia
have the same address, but they have different values. My purpose is to use const_cast
to modify a constant value, but as the result shows that it does not work.
有人知道为什么吗?
推荐答案
看到 10
的原因为 ia
打印很可能是编译器优化:它看到一个 const
对象,决定它不会改变,并用以下内容替换最后的打印输出:
The reason why you see 10
printed for ia
is most likely the compiler optimization: it sees a const
object, decides that it's not going to change, and replaces the last printout with this:
cout<< 10 <<" "<<*ppa<<endl;
换句话说,生成的代码具有 const的值
烘焙到二进制文件中。
In other words, the generated code has the value of the const
"baked into" the binary.
放弃最初被声明为 const <的对象的常量性。 / code>并写入该对象是未定义的行为:
Casting away the const-ness of an object that has originally been declared as const
and writing to that object is undefined behavior:
$ 5.2.11 / 7-注意:取决于类型该对象,通过由const_cast抛出const-qualifier68的指针,左值或指向数据成员的写入操作,可能会产生未定义的行为(7.1.5.1)。
$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
对象可能会放置在受保护的内存区域中,而您不能在其中写入内容。解决类型系统中的 const
-ness可能有助于您的程序编译,但是您可能会看到随机结果甚至崩溃。
Depending on the platform, const
objects may be placed in a protected region of memory, to which you cannot write. Working around the const
-ness in the type system may help your program compile, but you may see random results or even crashes.
这篇关于我们可以使用const_cast修改常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!