C++ 中 const 指针可变

Jay*_*esh 5 c++ pointers constants mutable

如果我像这样使用指针mutableconst

class Test
{
    public:
    mutable const int* ptr; // OK
};
Run Code Online (Sandbox Code Playgroud)

运行良好。

但是,如果我这样使用:

class Test
{
    public:
    mutable int * const ptr; // Error
};
Run Code Online (Sandbox Code Playgroud)

一个错误 :

prog.cpp:6:25: error: const 'ptr' cannot be declared 'mutable'
     mutable int * const ptr;
                         ^
prog.cpp: In function 'int main()':
prog.cpp:11:7: error: use of deleted function 'Test::Test()'
  Test t;
       ^
prog.cpp:3:7: note: 'Test::Test()' is implicitly deleted because the default definition would be ill-formed:
 class Test
       ^
prog.cpp:3:7: error: uninitialized const member in 'class Test'
prog.cpp:6:25: note: 'int* const Test::ptr' should be initialized
     mutable int * const ptr;
Run Code Online (Sandbox Code Playgroud)

为什么编译器在第二种情况下会出错?

Som*_*ude 7

const int * ptr;

第一个是指向常量数据的指针,这意味着您可以更改指针及其指向的位置,但无法更改它指向的数据。

int * const ptr;

第二个是指向非常量数据的常量指针,这意味着您必须在构造函数中初始化该指针,然后不能使其指向其他任何地方。但它指向的数据可以修改。

mutable两种情况下的部分都适用于指针,即实际的成员变量,而不是它指向的数据。由于变量不能同时是 antmutable和ant,因此您应该收到一条错误消息。const


son*_*yao 5

第二种情况会导致错误,因为mutableconst不能混合;mutable只能与非常量数据成员一起使用。

适用于非引用非 const 类型的非静态类成员,并指定该成员不会影响类的外部可见状态(通常用于互斥体、备忘录缓存、惰性求值和访问检测)。const 类实例的可变成员是可修改的。

顺便说一句,以下代码会导致相同的错误。

class Test
{
    public:
    mutable const int x; // Error;
    mutable int const x; // ditto;
};
Run Code Online (Sandbox Code Playgroud)

第一种情况很好,因为const int*不是const指针,而是指向 的指针const。这意味着修改指针本身就可以了,并且可以对其进行标记mutable。(但您无法修改被指点。)

BTWconst指向const(例如mutable const int* const ptr;)的指针也会导致相同的错误。