sha*_* vy 3 c++ pointers const mutable
我没有找到任何与mutable constSO 相关的主题.我已经将代码减少到最小的工作代码(在visual studio上).如果我们取消注释//*data = 11;,编译器会抱怨const-ness.我想知道怎么mutable const运作.
class A
{
public:
void func(int & a) const
{
pdata = &a;
//*pdata = 11;
}
mutable const int * pdata;
};
int main()
{
const A obj;
int a = 10;
obj.func(a);
}
Run Code Online (Sandbox Code Playgroud)
这个例子有点令人困惑,因为mutable关键字不是类型说明符的一部分const int *.它被解析为类似的存储类static,所以声明:
mutable const int *pdata;
Run Code Online (Sandbox Code Playgroud)
说这pdata是一个指向const int的可变指针.
由于指针是可变的,因此可以在const方法中进行修改.它指向的值是const,不能通过该指针修改.
你理解mutable const班员毫无意义是正确的。您的示例更多地展示了如何const使用指针的怪癖。
考虑下面的类。
class A {
const int * x; // x is non-const. *x is const.
int const * y; // y is non-const. *y is const.
int * const z; // z is const. *z is non-const.
};
Run Code Online (Sandbox Code Playgroud)
所以const根据你写的地方有不同的含义。
由于x和y是非常量的,因此使它们可变并不矛盾。
class A {
mutable const int * x; // OK
mutable int const * y; // OK
mutable int * const z; // Doesn't make sense
};
Run Code Online (Sandbox Code Playgroud)
mutable const听起来很矛盾,但实际上有一个完全合理的解释。 const int *意味着不能通过该指针更改所指向的整数值。 mutable意味着指针本身可以更改为指向另一个 int 对象,即使该成员所属A的对象pdata本身是 const 的。同样,无法通过该指针更改指向的值,但该指针本身可以重新定位。
当赋值语句取消注释时,您的代码将失败,因为该赋值违反了您不修改指向值(部分const int *)的承诺。