The Double Life of Objects -- Andrzej Krzemieński
In the world of C++, the concept of object lifetime and const
ness can become a bit hazy when copy elision, a popular optimization technique, comes into play. In this article, Andrzej Krzemieński explores the intricacies of object lifetimes and const
ness, using a class called Rng
to illustrate how objects can appear const
in one context and non-const
in another due to copy elision. He'll also delve into the motivations behind C++'s handling of const
objects and how it impacts program behavior.
The Double Life of Objects
by Andrzej Krzemieński
From the article:
Some common knowledge: the lifetime of the object starts when its initialization is complete. Based on this we can get some further expectations: an object becomes
const
only after its initialization is complete. But this lifetime property of objects becomes blurred when copy elision comes into play. When a copy is elided, we have a situation where we would otherwise have two objects, each initialized separately, but now they are blended into one, its life time spanning across the caller and the calle, which has a number of surprising effects, receiving two initializations being one of them.In the following examples we will use class
Rng
that is quite small but convincing: you define a class when you need to maintain the invariant. Our class represents a range of integers between the minimum and maximum values.
Now, let’s try to use it in a somewhat artificial program: