As a novice C++ programmer there are some constructs that look still very obscure to me, one of these is const
. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why not to use them?
C++ – How Many and Which Are the Uses of const?
c++constants
Best Answer
Trying to collect some uses:
Binding some temporary to reference-to-const, to lengthen its lifetime. The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called:
Explanation, using code:
This trick is used in Alexandrescu's ScopeGuard utility class. Once the temporary goes out of scope, the destructor of Derived is called correctly. The above code misses some small details, but that's the big deal with it.
Use const to tell others methods won't change the logical state of this object.
Use const for copy-on-write classes, to make the compiler help you to decide when and when not you need to copy.
Explanation: You might want to share data when you copy something as long as the data of the originally and the copie'd object remain the same. Once one of the object changes data, you however need now two versions: One for the original, and one for the copy. That is, you copy on a write to either object, so that they now both have their own version.
Using code:
The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write
std::string
. Both strings, even though they are distinct objects, share the same memory for their string data. Makingb
non-const will prefer the non-const version of theoperator[]
and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data ofa
!For the copy-constructor to make copies from const objects and temporaries:
For making constants that trivially can't change
For passing arbitrary objects by reference instead of by value - to prevent possibly expensive or impossible by-value passing