我希望有人能准确地阐明 C++ 中未定义行为的含义。给定以下类定义:
class Foo
{
public:
explicit Foo(int Value): m_Int(Value) { }
void SetValue(int Value) { m_Int = Value; }
private:
Foo(const Foo& rhs);
const Foo& operator=(const Foo& rhs);
private:
int m_Int;
};
如果我正确理解了以下代码中对引用和指针的两个 const_casts 将删除 Foo 类型的原始对象的 const-ness,但是通过指针或引用修改此对象的任何尝试都会导致未定义的行为。
int main()
{
const Foo MyConstFoo(0);
Foo& rFoo = const_cast<Foo&>(MyConstFoo);
Foo* pFoo = const_cast<Foo*>(&MyConstFoo);
//MyConstFoo.SetValue(1); //Error as MyConstFoo is const
rFoo.SetValue(2); //Undefined behaviour
pFoo->SetValue(3); //Undefined behaviour
return 0;
}
令我困惑的是为什么这似乎有效并且会修改原始的 const 对象,但甚至不会提示我警告以通知我此行为未定义。我知道 const_casts 从广义上讲是不受欢迎的,但我可以想象这样一种情况,即缺乏对 C 风格转换可能导致 const_cast 的认识的情况可能会在不被注意的情况下发生,例如:
Foo& rAnotherFoo = (Foo&)MyConstFoo;
Foo* pAnotherFoo = (Foo*)&MyConstFoo;
rAnotherFoo->SetValue(4);
pAnotherFoo->SetValue(5);
在什么情况下,这种行为可能会导致致命的运行时错误?是否可以设置一些编译器设置来警告我这种(潜在的)危险行为?
注意:我使用 MSVC2008。