VC++ 2010 问题:
const bool bNew = true;
const_cast<bool&>(bNew) = false;
if(bNew)//bNew is false here, but
{
int i = 0;//this line will be executed
}
为什么?
谢谢。
最佳答案
来自 C++03 标准的第 7.1.5.1/4 节:
Except that any class member declared
mutable
(7.1.1) can be modified, any attempt to modify aconst
object during its lifetime (3.8) results in undefined behavior.
您将 bNew
声明为一个 const
对象,然后您通过显式转换它来修改它来破坏类型系统。因此,您调用了未定义的行为,这意味着任何事情都可能发生。
关于c++ - const_cast with bool : if condition ignored,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417462/