Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define a mutable pointer to a const object?

I have a class that contains a pointer to a constant VARIANT value outside the class, but sometimes I want to change this pointer to refer to a VARIANT member object of the class itself.

Most instances of this class will be const, so I have to declare the pointer as mutable.

In Visual C++ this code seems to do what I want:

VARIANT mutable const* m_value;

However, since mutable is meant to be a property of the pointer and not the pointee, I would think this to be the correct syntax:

VARIANT const * mutable m_value;

Similar to how you define a constant pointer (and not a pointer to a const object). Visual C++ does not accept this variant though.

warning C4518: 'mutable ' : storage-class or type specifier(s) unexpected here; ignored

Is Visual C++ right, or am I missing something? Could another more standard-conformant compiler behave differently?

like image 449
Niklas Bäckman Avatar asked Dec 12 '22 18:12

Niklas Bäckman


2 Answers

Comeau online seems to agree with VC++ here.

And it also makes sense! A class member can only be mutable once and there is no such thing as a non-const pointer to a mutable const object. "Mutable const object" doesn't make sense.

You should put the mutable in front of your declaration, as it is in the same area as, for example, static:

class A {
  static  int const* m_p1; // static modifiable pointer to a const object;
  mutable int const* m_p2; // mutable pointer to a const object
  ...
  mutable int *const m_p3; // DOES NOT MAKE sense

m_p3 does not make sense - you declare the member as "always mutabel" and as "always const" at the same time.

like image 50
Martin Ba Avatar answered Jan 15 '23 09:01

Martin Ba


VC++ is right. In this case mutable is a storage-class-specifier, like static, extern and register. Just like

int const* static foo;

won't compile, as a specifier must appear at the beginning of a declaration.

like image 32
kennytm Avatar answered Jan 15 '23 09:01

kennytm