Should members usually not be const in C++ classes?
I suggest you disregard how variable are declared "usually". The frequency of the occurrence of const
is not something that should make you decide whether the next variable you're going to declare is or is not const
.
Members should be const
if their value is not supposed to change after initialization throughout the execution of your program. Otherwise, they should not be const
. This is a semantic property of your data, and the only criterion you should use for deciding whether to make a variable const
or not is the nature of your variable with respect to value change.
May it change, or shall it stay unchanged? In the latter case, definitely do make it const
.
This has to imply that internally, std::string has only non-const member variables right?
No, it doesn't imply it, although that probably happens to be the case for std::string
.
The important thing is that there are not only const
members in your class (as long as you want to move from it and your class encapsulates some resource, of course), so that those members which actually can be used to tell whether an object has been moved from are modifiable.
When you move from an object, what you're left with is a skeleton. The move constructor or move assignment operator needs a way to "flag" this moved-from object as a skeleton. Normally, this follows naturally from the process of "stealing the guts" of the moved from object, i.e. copying some pointers and setting them to null - this way, the destructor and assignment operators won't try to release them. In order to flag the moved-from object as a "zombie", obviously you need some modifiable member variable(s).
However, there's nothing wrong with also having some const
members in your class. const
is an important modifier which makes the semantics of your program clearer, and your program less likely to break it. Whenever appropriate (i.e. whenever the value of A variable won't change throughout the execution of your program after initialization), use it.
Simply, const
member variables won't be modified by a move constructor or move assignment operator (in fact, they won't be modified by any function); but again, that doesn't mean they cannot be present.