gpt4 book ai didi

c++ - 常量和可变

转载 作者:可可西里 更新时间:2023-11-01 17:31:07 28 4
gpt4 key购买 nike

我刚看到这个代码片段,但我不明白它是如何编译的:

class temp {
int value1;
mutable int value2;
public:
void fun(int val) const
{
((temp*) this)->value1 = 10;
value2 = 10;
}
};

这行是什么意思

((temp*) this)->value1 = 10;

value1 被分配给 10,没有任何错误。但是 value1 不是可变的。这是如何编译的?

最佳答案

当一个成员变量没有mutable限定词时,当一个对象是const时你不能修改它。

当成员变量具有mutable 限定符时,即使对象是const,您也可以修改它。

简单的例子:

struct Foo
{
int var1;
mutable int var2;
};

const Foo f{};
f.var1 = 10; // Not OK
f.var2 = 20; // OK

当你有:

void fun(int val) const
{
((temp*) this)->value1 = 10;
value2 = 10;
}

您正在绕过对象的 const 特性并以您不应该的方式更改它。这受未定义行为的影响。

就编译器而言,该代码等同于:

void fun(int val) const
{
temp* ptr = (temp*)this

// The compiler does not know how you got ptr.
// It is able to modify value1 through ptr since ptr
// points to a non-const object.
ptr->value1 = 10;

value2 = 10;
}

关于c++ - 常量和可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233771/

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