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;
时间: 2024-09-29 05:23:11