Const propagation for pointers
A common mistake when writing const-correct code in C++ is that a const initialized object can still manipulate the values that member pointers points at. The following example illustrates the problem:
class Foo { public: Foo(int* ptr) : ptr_{ptr} {} auto set_ptr_val(int v) const { *ptr_ = v; // Compiles despite function being declared const! } private: int* ptr_{}; }; auto main() -> int { const auto foo = Foo{}; foo.set_ptr_val(42); }
Although the function set_ptr_val()
is mutating the int
value, it's valid to declared it const
since the pointer ptr_
itself is not mutated, only the int
object that the pointer is pointing at.
In order to prevent this in a readable way, a wrapper called std::experimental::propagate_const
has been added to the std
library extensions (included in, as of the time of writing this, the latest versions of Clang and GCC). Using propagate_const
, the function set_ptr_val()
will not compile. Note that propagate_const
...