考虑以下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';
}
它似乎工作正常,但它是否绝对安全?
我只是修改一个mutable
字段,但完全剥离其const
上下文让我感到不安。