Managing objects’ lifetime
One of the main disastrous issues that can happen with asynchronous operations is that, when the operation takes place, some of the required objects have been destroyed. Therefore, managing objects’ lifetimes is crucial.
In C++, an object’s lifetime begins when the constructor ends and ends when the destructor begins.
A common pattern used to keep objects alive is to let the object create a shared pointer instance to itself, ensuring that the object remains valid as long as there are shared pointers pointing to it, meaning that there are ongoing asynchronous operations needing that object.
This technique is called shared-from-this
and uses the std::enable_shared_from_this
template base class, available since C++11, which provides the shared_from_this()
method used by the object to obtain a shared pointer to itself.
Implementing an echo server – an example
Let’s see how it works by creating an echo server....