Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member assignment in a const function

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?

like image 928
Fredrik Ullner Avatar asked Nov 25 '09 12:11

Fredrik Ullner


1 Answers

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.

like image 171
Steve Gilham Avatar answered Oct 01 '22 18:10

Steve Gilham