修改常量对象 [英] Modifying constant object

查看:84
本文介绍了修改常量对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在通过面试问题寻找初级C ++开发人员的职位。问题是(quote):

I was looking through the interview questions to a junior C++ developer position. The question is (quote):


以下代码正确吗?



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

我会回答:


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

The code itself is valid according to the C++03 and c++11 standards and will compile successfully. But it may invoke an undefined behavior during assignment pointer->i = 0; if the instance of the class on which foo() is being called is declared as const.

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

I mean that following code will compile successfully and result in undefined behaviour.

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;
}

我的答案正确吗?或者我错过了什么?谢谢。

Is my answer correct or I am missing something? Thank you.

推荐答案

我首先要问一下正确的不明确定义是什么意思。您需要了解程序的规范及其预期的行为

I would first ask what is meant by their ambiguous definition of "correct". You need to know the specification of the program and its intended behaviour.

如您所说,如果他们只是问它是否可以编译,那么答案是是。但是,如果他们确定正确无误,那么您可以讨论您在问题中陈述的事实。

As you said, if they're just asking if it compiles then the answer is 'yes'. However, if they determine correct to be safe to do, then you can discuss the facts that you state in your question.

通过这种方式回答,面试的人可以看到您如何分析自己的要求,而不是直接回答,我认为这是一件好事。

By answering this way, the person interviewing can see how that you're analysing what you're being asked, rather than jumping straight into answering, which in my opinion is a good thing to do.

这篇关于修改常量对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆