gpt4 book ai didi

c++ - 修改常量对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:39 26 4
gpt4 key购买 nike

我正在查看初级 C++ 开发人员职位的面试问题。问题是(引用):

Is the following code correct?

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

我会回答:

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.

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

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"。但是,如果他们确定这样做是安全的,那么您可以讨论您在问题中陈述的事实。

通过这种方式回答,面试者可以看到你是如何分析你被问到的问题,而不是直接跳到回答中,我认为这是一件好事。

关于c++ - 修改常量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17833558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com