gpt4 book ai didi

c++ - “可变”变量只能通过一种 const 方法可变吗?

转载 作者:太空狗 更新时间:2023-10-29 23:20:25 27 4
gpt4 key购买 nike

今天我了解了 C++ 中的 mutable 关键字,并想在我的代码中使用它。

我有一个包含许多 const 方法的类,其中一个应该能够修改对象的一些变量(保存对象的逻辑状态)。但是我不想让所有 const 方法修改变量,只修改选定的一个。有什么办法吗?也许使用 const_cast

(我说的代码是 Union-Find structure 的实现。Find 操作不会改变结构的逻辑状态(它只搜索树的根),但通过进行所谓的路径压缩来改变物理状态)

谢谢!

编辑:我添加了我所指代码的摘录:

class UnionFind {
public:
void Union(int a, int b) {...}

int Find(int x) const {
// logically, this method is const
while(x != parents[x]) {
// path compression
// the next three lines modify parents and sizes,
// but the logical state of the object is not changed
sizes[parents[x]] -= sizes[x];
sizes[parents[parents[x]]] += sizes[x];
parents[x] = parents[parents[x]];

x = parents[x];
}
return x;
}

int someOtherMethodThatAccessesParents() const {
// this method does access parents, but read only.
// I would prefer if parents behaved like if it was
// not 'mutable' inside this method
...
}

private:
// these have to be mutable if I want the Find method
// to be marked const (as it should be)
// but making them mutable then does not enforce
// the physical non-mutability in other const methods :(
mutable std::vector<int> parents;
mutable std::vector<int> sizes;
};

最佳答案

乍一看,除非使用讨厌的 const_cast,否则这是无法实现的。但不要这样做,因为在最初声明为 const 的 const_cast 之后尝试修改变量的行为是未定义的。

但是,使用友元来实现您想要的可能是可行的,因为可以在逐个函数的基础上控制它,而正如您正确指出的那样,可变性是不可能的。

将要修改的变量放在基类中,并标记为私有(private)。也许为该成员提供“getter”功能。该函数将是 const 并且可能会返回对该成员的 const 引用。然后使您的函数成为该基类的友元。该函数将能够更改该私有(private)成员的值。

关于c++ - “可变”变量只能通过一种 const 方法可变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41127495/

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