对于给定的函数/代码块,是否可以只将成员变量视为可变?
例如
class Foo() {
int blah;
void bar() const {
blah = 5; // compiler error
}
void mutable_bar() const {
blah = 5; // no compiler error
}
}
注意:在这种情况下,我不想去掉 mutable_bar 中的常量,因为逻辑常量将被保留。
同样的问题,但观点不同:我能否以某种方式将 mutable 关键字应用于方法而不是变量?
最佳答案
不,这是不可能的,至少在 C++ 中是这样。您需要 mutable
或非 const
函数。
还有 const_cast
不要用它来修改东西。如果您修改 const_cast
ed const
值,您会得到未定义的行为。
5.2.11 常量转换
7 [ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier73 may produce undefined behavior (7.1.6.1). —end note ]
7.1.6.1 cv 限定符
4 Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
....
5 For another example
struct X {
mutable int i;
int j;
};
struct Y {
X x;
Y();
};
const Y y;
y.x.i++; // well-formed: mutable member can be modified
y.x.j++; // ill-formed: const-qualified member modified
Y* p = const_cast<Y*>(&y); // cast away const-ness of y
p->x.i = 99; // well-formed: mutable member can be modified
p->x.j = 99; // undefined: modifies a const member
—end example ]
关于c++ - 成员变量的临时可变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256065/