Const Correctness Pitfalls¶
Const correctness is not "add const until the compiler stops complaining".
It changes which operations are legal, which objects may be modified, and how
long a temporary lives. The three failures below are common because they look
correct at a glance.
The runnable companion is:
1. A reference can extend a temporary; a pointer cannot¶
const std::string& ref = std::string("temporary"); // lives as long as ref
const char* ptr = std::string("temporary").c_str(); // dangles after this line
Binding a temporary to a const reference extends the temporary's lifetime to
the reference's scope. That is why ref is safe. c_str() returns a pointer to
the temporary's buffer, and a pointer does not extend the temporary's lifetime;
after the full expression, ptr points at storage that no longer exists.
The standard rule is in [class.temporary] (temporary objects and lifetime
extension). The important distinction is reference binding, not "const
makes it safe":
const std::string& ref = std::string("temporary");— lifetime extendedconst char* ptr = std::string("temporary").c_str();— no extension
For a string_view, the same distinction applies: a view does not own its
characters. See the dangling string_view Atlas entry
for the CI-verified version.
2. mutable makes a write legal; it does not make it thread-safe¶
class Cache {
public:
int get(int key) const {
auto it = cache_.find(key);
if (it != cache_.end()) return it->second;
int value = compute(key);
cache_[key] = value; // legal because cache_ is mutable
return value;
}
private:
mutable std::map<int, int> cache_;
int compute(int key) const;
};
This is legal C++. A const member function promises not to modify the object's
observable state through a non-mutable path. A mutable member is explicitly
excluded from that promise, so a cache can be updated from a const method.
Without mutable, cache_[key] = value would be a compile error.
Two cautions:
mutableis for logical constness (caches, memoization, instrumentation), not for hiding a design where the method should really be non-const.- A
constmember function is not automatically thread-safe. If two threads callgeton the sameCache, the mutable map is still shared state and still needs synchronization.
The relevant rules are [dcl.type.cv] for cv-qualified objects and
[expr.prim.this] for this inside a const member function. The common myth
"writing in a const method is always UB" is wrong; the compiler decides based on
the member's declared mutability.
3. const_cast can only remove const from an object that was not originally const¶
int value = 42;
const int& view = value;
int* p = const_cast<int*>(&view);
*p = 100; // legal: the original object is non-const
const int constant = 42;
int* q = const_cast<int*>(&constant);
*q = 100; // undefined behavior
const_cast changes the type of an expression; it does not change the
constness of the underlying object. Modifying an object that was defined as
const is undefined behavior under [dcl.type.cv]. A cast that removes
const from a view of an originally non-const object is legal; the cast itself
is governed by [expr.const.cast].
This is why APIs often accept const T& and still return a mutable view through
a separate, explicitly named method. The type system is telling you which
objects are safe to modify; const_cast should not be used to silence that
information.
What to do instead¶
- Prefer
const T&for read-only parameters and returns when ownership is not transferred. - Keep the owner alive for the full lifetime of a pointer or view.
string_view,span, and raw pointers are non-owning types. - Use
mutableonly for logical constness, and document the synchronization requirements of the mutable state. - Use
const_castonly when the object is known to be non-const, preferably at a narrow API boundary with a comment explaining why. - Do not assume
-Wcast-qualcatches every unsafe cast; it catches some syntactic cases, not the lifetime or original-definition mistakes.
Review checklist¶
- Does a reference bind directly to the temporary, or does a pointer/view merely point into it?
- Is a
constmethod modifying amutablemember? If so, is concurrent access synchronized? - Does a
const_castremove const from an object that was originally defined as non-const? - Is the owner still alive at every use of the pointer, view, or reference?