Member-only story

Modern C++ : ensuring const-correctness

Gajendra Gulgulia
3 min readOct 12, 2021

--

In this article I’d like to discuss the shortcoming of (modern) C++ with respect to const pointers and how to alleviate them with the std::experimental::propagate_const utility wrapper available with C++17.

Given that pointers (smart or raw) are an integral part of C++ and the fact that they are used extensively, in day to day programming practices, this issue is more than trivial and need not be overlooked.

In the first section I’ll demonstrate the problem with propagating const-correctness through pointers and in the second section, I’ll present the solution. Complete code examples are presented (apart from the output in the code block) which can be copied and pasted to your favorite editor. Please remember to compile the code with at least C++17 compiler.

1. Introduction : The problem with pointers and `const`-correctness

Pointers in C++ have a sneaky shortcoming that when calling a method on a const pointer, it doesn’t guarantee to invoke a corresponding const method on it, if available. In C++ terms this would mean that the const correctness is respected through all paths when member functions are invoked on an object that is marked as const .

1.1 const-correctness and const-path : without pointers

--

--

Gajendra Gulgulia
Gajendra Gulgulia

Written by Gajendra Gulgulia

I'm a backend software developer and modern C++ junkie. I run a modern cpp youtube channel (https://www.youtube.com/@masteringmoderncppfeatures6302/videos)

No responses yet