Is this undefined behavior with const_cast? [duplicate]

南笙酒味 提交于 2019-11-26 12:47:28

问题


This question already has an answer here:

  • behavior of const_cast in C++ [duplicate] 3 answers

What is happening here?

const int a = 0;
const int *pa = &a;

int *p = const_cast<int*>(pa);
*p = 1;  // undefined behavior ??
cout << a << *p;  // ??

My compiler outputs 0 and 1, but address of \'a\' and value of \'p\' is the same, so I\'m confused how is this possible.


回答1:


Quote from cppreference:

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.

So yes, modifying constant variables is undefined behavior. The output you see is caused by the fact that you tell the compiler that the value of a will never change, so it can just put a literal 0 instead of the variable a in the cout line.




回答2:


§7.1.6.1 [dcl.type.cv]/p4:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.




回答3:


Attempting to write on a const value is undefined behavior, for example to allow the compiler to allocate const values into read only memory (usually in code segment) or inline their value into expressions at compile time, which is what happens in your case.



来源:https://stackoverflow.com/questions/25209838/is-this-undefined-behavior-with-const-cast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!