gpt4 book ai didi

c++ - 为什么可以通过使用指向对象成员的指针的 const 成员函数来修改对象状态?

转载 作者:行者123 更新时间:2023-12-05 03:44:19 31 4
gpt4 key购买 nike

为什么这段代码没有产生编译错误:

class C
{
int _i{ 123 };
int* ptr{ &_i };
public:
int& i() const { return *ptr; }
};

int main()
{
C const c;
c.i() += 321;
return c.i();
}

标准中是否有关于此行为的一些文字?当然,也许没有必要指向可以直接访问的成员,但是拥有堆上的资源也可以看作是对象的一部分。

最佳答案

在对象的构造和销毁过程中,成员不是const。这意味着您可以存储一个指向某个成员的非常量指针,该成员在构造对象后将成为常量。使用该指针更改 const 对象的值是未定义的行为。引用 cppreference :

Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

并引用 [dcl.type.cv]/4 :

Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.

关于c++ - 为什么可以通过使用指向对象成员的指针的 const 成员函数来修改对象状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66505784/

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