标签:style blog color io ar div sp log on
const int x=4; int& y = const_cast<int&>(x); ++y;
这时访问x,x会是多少呢?
根据C++11标准7.1.6.1.4:
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. (ISO/IEC 14882:2011)
尝试通过const_cast消除const来修改x的值有程序崩溃的可能,虽然在某些平台上可能会输出4(编译期间优化)。
同样,下面的code也是不安全的:
const int x=4; int& y = (int&)x; ++y;
[C/C++]用const_cast修改const变量会得到什么结果?
标签:style blog color io ar div sp log on
原文地址:http://www.cnblogs.com/gomopsivarh/p/3957907.html