c++ - 成员变量的临时可变性

标签 c++ mutable

对于给定的函数/代码块,是否可以只将成员变量视为可变?

例如

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_casted 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/

相关文章:

c++ - 在没有 IDE 的情况下用 C++ 手工编写 Windows GUI

c++ - 我如何等到变量达到一定数量才做某事?

c++ - 双括号初始化

.net - F# : Is it okay to use mutable .Net List 将元素添加到同一列表

javascript - 可变变量的 JS 闭包

buffer - 在 Rust 中创建字节缓冲区

c++ - 用于在 C++ 中包装整数的干净、高效的算法

c++ - 具有 unique_ptr 的类的复制构造函数

arrays - 奇怪的 ArrayBuffer 行为

python - 列表列表更改意外地反射(reflect)在子列表中