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?
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
or [from other response, thanks :P]:
Making it mutable effectively means you get implicit
const_casts inconstmember functions, which is generally what you should be steering towards when you find yourself doing loads ofconst_casts onthis. 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
mutableand lots ofconst_casts can definitely be symptoms of bad smells in your code. From a conceptual point of view, casting away constness or usingmutablecan 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
mutablearound like pixie dust to make stuff work, butmutableis 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.