c++ - const_cast with bool : if condition ignored

标签 c++ visual-c++ casting boolean constants

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 a const 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/

相关文章:

c++ - 链接我的项目 C++ 的问题

c++ - 不匹配运算符,为什么这段代码没有得到 cin?

windows - 重新连接到命名管道时出现问题

c++ - 将 '>' 重载为非成员函数

在 C 中从 int 转换为 float 会改变值

arrays - Swift:在调用 indexOf 时无法将类型的值转换为 @noescape,在使用过滤函数进行过滤之后

c++ - 如何将 constexpr 字符串文字传递给其他函数

c++ - 即使没有要复制的对象,复制构造函数也会自动调用吗?

c++ - 重新打开一个关闭的文件流

c - 用户扫描号码的模 10^9 + 7