修改常量对象

Kol*_*nya 6 c++ const constants undefined-behavior c++11

我正在通过面试问题向初级C++开发人员的位置看.问题是(引用):

以下代码是否正确

struct Foo
{
    int i;
    void foo ( void ) const
    {
        Foo* pointer = const_cast<Foo*>(this);
        pointer->i = 0;
    }
};
Run Code Online (Sandbox Code Playgroud)

我会回答:

代码本身根据C++ 03和c ++ 11标准有效,并且将成功编译.但它可能在赋值指针 - > i = 0期间调用未定义的行为; 如果调用foo()的类的实例声明为const.

我的意思是下面的代码将成功编译并导致未定义的行为.

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;
}
Run Code Online (Sandbox Code Playgroud)

我的回答是正确的还是我错过了什么?谢谢.

The*_*ght 5

我首先会问他们对"正确"的模糊定义是什么意思.您需要知道程序的规范及其预期行为.

正如你所说,如果他们只是问它是否编译,那么答案就是"是".但是,如果他们认为安全做得正确,那么您可以讨论您在问题中陈述的事实.

通过回答这种方式,面试的人可以看到你是如何分析你被问到的,而不是直接回答,这在我看来是一件好事.