【问题标题】:Is const_casting a mutable field safe?const_casting 可变字段安全吗?
【发布时间】:2012-11-19 14:51:58
【问题描述】:

考虑以下 C++03 程序:

#include <iostream>

struct T
{
    mutable int x;

    T() : x(0) {}
};

void bar(int& x)
{
   x = 42;
}

void foo(const T& t)
{
   bar(const_cast<int&>(t.x));
}

int main()
{
   T t;
   foo(t);
   std::cout << t.x << '\n';
}

appears to work,但它肯定安全吗?

我只是修改了一个 mutable 字段,但是完全剥离了它的 const 上下文让我很紧张。

【问题讨论】:

    标签: c++ constants c++03


    【解决方案1】:

    这是安全的,但也是不必要的。因为mutablet.x 已经是int&amp; 类型。您的示例程序works fine if the cast is removed entirely

    【讨论】:

    • 哦,该死的......我未能将我在真实项目中创建字段mutable 的标题更改上传到我的编译服务器,因此我错过了该字段已经是非-const 类型。使整个问题变得毫无意义……呵呵。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 2010-11-20
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多