Mutable T* const?

The question is purely ideological, or even rhetorical.

You need to change the class field in a constant method. Let's say the trolleys we got in the inheritance hierarchy, and your field want to change.

The first output — mutable. Everything works, but some say that mutable is bad and generally a crutch.

The second way is to declare our pointer to the desired data. Since the constness refers to the pointer to the data can be easily changed.

It is clear that the situation itself is slippery, but quite frequent. I believe that mutable honest, it's a clear indication that we are going to break the rules. And the pointer is masking the same. But there are absolutely opposite opinion.

What do you think?
October 8th 19 at 02:04
4 answers
October 8th 19 at 02:06
mutable indicates that from our point of view, the attribute is not very important and does not affect the constness of the class. Ie for example, if we pass a class argument to a function, for example, nothing terrible will happen if the mutable attributes will be changed. Ie if you use mutable, you need to answer the question: does the attribute very important information or not.

And as with T* const in this situation it is a crutch. Using mutable we declare that we are going to change the attribute, but T* const this, just not talking. And then it will be hard to figure out who is who.
October 8th 19 at 02:08
There is another option — const_cast.
as for me better to be mutable. - marjolaine commented on October 8th 19 at 02:11
Yes, that's an option. but in my opinion the worst. after a const_cast to change everything in a row, even non-const methods to call, and this is a game without rules. const_cast — a crutch by definition, any except that in the case of libraries that are written without Kostov. - jorge_Wilderman commented on October 8th 19 at 02:14
October 8th 19 at 02:10
If the constness of You had inherited and You can't change that, choose any option and do not listen to all the snobs on "ugliness, unethical" and so on. All these "unethical" means in the language you just created in order to handle unusual situations.
If on, then I would choose mutable.
For example, in order to do a getItem for potoko-safe, partial container may require the use of mutex.lock(). In this case, the getItem is semantically a constant, and must be declared as const the getItem; but to lochit mutex in this method, you must change it. Where You hadn't seen the solution to such problems, I bet that the mutex is declared as a mutable field of a class.
October 8th 19 at 02:12
If we are talking about any particular method, I'd use const_cast. It is easily searched in the code and shows the obvious crutch.
If a lot of them — then mutable.

Find more questions by tags C++