Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutable with const pointer in C++

If I use mutable with const pointer like this:

class Test
{
    public:
    mutable const int* ptr; // OK
};

It's working fine.

But, If I use like this :

class Test
{
    public:
    mutable int * const ptr; // Error
};

An error :

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;

Why does compiler give an error in second case?

like image 696
Jayesh Avatar asked Dec 13 '22 20:12

Jayesh


1 Answers

const int * ptr;

The first is a pointer to constant data, which means you can change the pointer and where it points to, but you can't change the data it points to.

int * const ptr;

The second is a constant-pointer to non-constant data, which means you must initialize the pointer in your constructor(s) and then you can't make it point anywhere else. The data it points to can be modified though.

The mutable part in both cases applies to the pointer, the actual member variable, not the data it points to. And since the variable can't be both mutable and constant at the same time you should get an error message for that.

like image 179
Some programmer dude Avatar answered Jan 15 '23 12:01

Some programmer dude