Brian
Brian

Reputation: 2619

Temporary mutability of a member variable

Is it possible to have a member variable only be considered mutable for a given function/code block?

e.g.

class Foo() {
  int blah;
  void bar() const {
    blah = 5; // compiler error
  }
  void mutable_bar() const {
    blah = 5; // no compiler error
  }
}

note: in this case I do NOT want to get rid of the const at mutable_bar since logical const will be preserved.

Same question, but different perspective: Can I somehow apply the mutable keyword to a method instead of a variable?

Upvotes: 0

Views: 237

Answers (3)

alexrider
alexrider

Reputation: 4463

No, it is not possible, at least in C++. You need either mutable or non const function.
Also there is const_cast don't use it to modify things. In case if you modify const_casted const value you get Undefined Behaviour.

5.2.11 Const cast

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 The cv-qualifiers

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 ]

Upvotes: 3

Mats Petersson
Mats Petersson

Reputation: 129424

It is technically possible to bypass the const in this case, by for example:

void mutable_bar() const {
    int& p_blah = const_cast<int&>(blah);

    p_blah = 5; // no compiler error
}

Or some similar construct. But you are really jumping through hoops to do something that you shouldn't be able to do. And as a comment on another post says, this is "undefined behavior", which means that in some cases it may not even work (or do what you expect it to do).

Upvotes: 1

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

You could use a const_cast to make the member not-const in selected cases. This, along with an according comment, might even be a relatively clean solution. At least it's explicit that you break the const in a restricted scope, instead of making it world-wide mutable.

Upvotes: 0

Related Questions