views:

263

answers:

5

I have a class member myMember that is a myType pointer. I want to assign this member in a function that is declared as const. I'm doing as follows:

void func() const
{
     ...
     const_cast<myType*>(myMember) = new myType();
     ...
}

Doing this works fine in VC++, but GCC gives an error with the message "lvalue required as left operand of assignment".

Making the member mutable allow me to simply remove the const_cast and assign the value. However, I'm not entirely sure that that comes with other side-effects.

Can I assign my member without having to make the member mutable? How? Are there any side-effects in making members mutable?

+10  A: 

This scenario -- an encapsulated internal state change that does not impact external state (e.g. caching results) -- is exactly what the mutable keyword is for.

Steve Gilham
Mutable is not good way if you want get write access to member in only one const-method.
Staseg
The externally observable state of the object must not change when writing to a mutable object. Making a member mutable just to circumvent an error in a const function is not legitimate if the change is externally visible, and may lead to undefined behavior. Legitimate uses of mutable include caching, where for example the same call twice returns the same result, but faster.
AshleysBrain
+4  A: 
class Class{
int value;
void func()const{
const_cast<Class*>(this)->value=123;
}
};
Staseg
You need cast object instead of a member.
Staseg
Thanks. I'm going by Ruben's first code since it looks cleaner. If I could, I'd mark both as "answer".
Fredrik Ullner
+4  A: 

The code wont actually work in VC++ - you're not updating the value (or at least it shouldnt), hence the warning from GCC. Correct code is

const_cast<myType*&>(myMember) = new myType();

or [from other response, thanks :P]:

const_cast<ThisType*>(this)->myMember = new myType();

Making it mutable effectively means you get implicit const_casts in const member functions, which is generally what you should be steering towards when you find yourself doing loads of const_casts on this. There are no 'side-effects to using mutable' other than that.

As you can see from the vehement debates circling this question, willy-nilly usage of mutable and lots of const_casts can definitely be symptoms of bad smells in your code. From a conceptual point of view, casting away constness or using mutable can have much larger implications. In some cases, the correct thing to do may be to change the method to non-const, i.e., own up to the fact that it is modifying state.

It all depends on how much const-correctness matters in your context - you dont want to end up just sprinking mutable around like pixie dust to make stuff work, but mutable is intended for usage if the member isnt part of the observable state of the object. The most stringent view of const-correctness would hold that not a single bit of the object's state can be modified (e.g., this might be critical if you're instance is in ROM...) - in those cases you dont want any constness to be lost. In other cases, you might have some external state stored somewhere ouside of the object - e.g., a thread-specific cache which also needs to be considered when deciding if it is appropriate.

Ruben Bartelink
Thanks. [min 15 chars]
Fredrik Ullner
I think while this works it is possibly the worst solution. It completely hides what happens (changing an internal state of an immutable instance) in a const-cast in the member function. "mutable" would be clearer (or using interfaces).
ur
casting away constness leads to undefined behavior. Use at your own risk. A better solution would be to make the method non const.
Martin York
+5  A: 

const_cast is nearly always a sign of design failure. In your example, either func() should not be const, or myMember should be mutable.

A caller of func() will expect her object not to change; but this means "not to change in a way she can notice"; this is, not to change its external state. If changing myMember does not change the object external state, that is what the mutable keyword is for; otherwise, func() should not be const, because you would be betraying your function guarantees.

Remember that mutable is not a mechanism to circunvent const-correctness; it is a mechanism to improve it.

Gorpik
+1 "const_cast is nearly always a sign of design failure"
ur
+1  A: 

As Steve Gilham wrote, mutable is the correct (and short) answer to your question. I just want to give you a hint in a different direction. Maybe it's possible in your szenario to make use of an (or more than one) interface? Perhaps you can grok it from the following example:

class IRestrictedWriter // may change only some members
{
public:
  virtual void func() = 0; 
}

class MyClass : virtual public IRestrictedWriter
{
public:
  virtual void func()
  {
    mValueToBeWrittenFromEverybody = 123; 
  }

  void otherFunctionNotAccessibleViaIRestrictedWriter()
  {
    mOtherValue1 = 123;
    mOtherValue2 = 345;
  }

  ...   
}

So, if you pass to some function an IRestrictedReader * instead of a const MyClass * it can call func and thus change mValueToBeWrittenFromEverybody whereas mOtherValue1 is kind of "const".

. I find mutable always a bit of a hack (but use it sometimes).

ur