我知道const应该谨慎地进行抛弃- 并且任何const从初始const对象中删除-ness 然后修改对象的尝试都会导致未定义的行为.如果我们想删除const-ness以便我们可以调用一个不修改对象的非const函数,该怎么办?我知道我们应该实际标记这样的功能const,但是假设我使用的是一个没有const可用版本的"坏"代码.
那么,总结一下,下面的代码是"安全的"吗?我的猜测是,只要你没有最终修改对象你就可以了,但我不是百分百肯定.
#include <iostream>
struct Foo
{
void f() // doesn't modify the instance, although is not marked const
{
std::cout << "Foo::f()" << std::endl;
}
};
int main()
{
const Foo foo;
const_cast<Foo&>(foo).f(); // is this safe?
}
Run Code Online (Sandbox Code Playgroud)