我正在查看一份初级C++开发人员职位的面试问题。问题是(引用):
以下代码是否正确?
struct Foo
{
int i;
void foo ( void ) const
{
Foo* pointer = const_cast<Foo*>(this);
pointer->i = 0;
}
};
我会这样回答:
根据C++03和c++11标准,代码本身是有效的,可以成功编译。
但是,如果调用 foo() 的类实例被声明为 const,则在赋值 pointer->i = 0; 期间可能会引发未定义的行为。
我的意思是,以下代码将成功编译并导致未定义的行为。
struct Foo
{
int i;
Foo ( void )
{
}
void foo ( void ) const
{
Foo* pointer = const_cast<Foo*>(this);
pointer->i = 0;
}
};
int main ( void )
{
Foo foo1;
foo1.foo(); // Ok
const Foo foo2;
foo2.foo(); // UB
return 0;
}
我的回答是否正确或者我有遗漏之处?谢谢。
const Foo foo; foo.foo();
不应该是未定义行为。使用一个mutable
成员会更好。 - StackedCrookedconst_cast
既安全又实用的使用示例,而不是一个玩具示例。 - Yakk - Adam Nevraumont