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 ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.