考虑以下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';
}It appears to work,但它确实安全吗?
我只修改了一个mutable字段,但是完全去掉它的const上下文让我很紧张。
发布于 2012-11-19 22:54:40
它是安全的,但也是不必要的。因为有了mutable,t.x已经是int&类型了。您的示例程序works fine if the cast is removed entirely。
https://stackoverflow.com/questions/13456242
复制相似问题