B
B
bfDeveloper2012-03-15 20:11:50
C++ / C#
bfDeveloper, 2012-03-15 20:11:50

Mutable or T* const?

The question is purely ideological or even rhetorical.
It is necessary to change the class field in the constant method. Let's say we got constancy according to the inheritance hierarchy, but we want to change some of our fields.
The first way out is mutable. Everything works, but some say that mutable is bad and generally a crutch.
The second way out is to declare our field as a pointer to the required data. Since the constancy will refer to the pointer, the data can be easily changed before.
It is clear that the situation itself is slippery, but quite frequent. I think mutable is fairer because it's a clear indication that we're about to break the rules. And the pointer is a disguise for the same. But there is also an absolutely opposite opinion.
What do you think?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
seagull, 2012-03-15
@seagull

mutable shows that from our point of view, the attribute is not very important and does not affect the constancy of the class. That is, for example, if we pass a class as an argument to a function, for example, then nothing bad will happen if the mutable attributes are changed. That is, when using mutable, you need to answer the question: Does the attribute contain very important information or not.
As for T* const, in this situation it is a crutch. Using mutable we declare that we are going to change the attribute, but T * const just does not say this. And then it will be hard to figure out who is who.

R
rtorsten, 2012-03-15
@rtorsten

There is another option - const_cast.

I
ixSci, 2012-03-16
@ixSci

If you inherited constancy and you cannot change it, then choose any option and do not listen to any snobs about “ugliness, unethical” and so on. All these "unethical" means in the language are just created in order to handle non-standard situations.
If on topic, then I would choose mutable.
For example, making getItem for a thread-safe, shared container might require the use of mutex.lock(). However, getItem is semantically const, and must be declared as getItem const; but in order to lock the mutex in this method, you need to change it. Wherever you find a solution to this problem, I'll bet that mutex will be declared as a mutable member of the class.

D
DenKon, 2012-03-15
@DenKon

If it's about a particular method, I would use const_cast. It is easily searched for in the code and points to an obvious crutch.
If there are many of them, then mutable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question