今日、私はC++でmutable
というキーワードを学び、自分のコードで使ってみたいと思っています。「可変」変数はconstメソッドの1つでしか変更できませんか?
私は多くのconst
メソッドを持つクラスを持ち、そのうちの1つはオブジェクトの変数の一部を変更できる(オブジェクトの論理状態を保存する)ことができるはずです。しかし、私はすべてのconst
メソッドに変数を変更させたいだけでなく、選択したものだけを変更したいと思います。それを行う方法はありますか?たぶんconst_cast
で?
(私が話しているコードは、Union-Find structureの実装です。Find
の操作では、構造の論理状態は変更されません(ツリーのルートのみが検索されます)が、物理状態が変更されます-called path compression)
ありがとうございます!
編集:私は、私が言及していたコードからの抜粋を追加しました:あなたはmutable
を使用するために余裕があれば
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;
};
物理ブロックと論理ブロックについて学ぶhttp://stackoverflow.com/a/3830484/151641 – mloskot
メンバーを変更可能と宣言した場合は、そのクラスのメソッドから変更できます。プライベートであると宣言して、サブクラスはそれにアクセスすることができず、優れたエンジニアリング手法を使用してルールを適用します。あなたのコードレビューがそのような誤用を拾うことができなければ、クラスが大きすぎるかもしれないことを示唆しています。 –
私はこれまでプロダクションコードでmutableを使用していた唯一の時は、 'std :: mutex'をmutableとしてマークすることで、constメソッドは実行中の状態の変化を防ぐことができると確信しています。 –