⚪ Together with the callback function: shared_from_this();
std::enable_shared_from_this is a C++ functionality, added since C++11, that allows a class to create shared instancesshared_ptr of itself.
This mechanism is useful when you need to create a shared_ptr inside a method of the class itself, especially to avoid duplication and maintain the correct reference count.
Usage
First of all, your class needs to inherit publicly(std::enable_shared_from_this<T>) for your class type, example:
The member function of this class that has return type: shared_ptr will no longer return *this but instead shared_from_this(), example:
The use of *this is not appropriate, because it does not increment the reference count of shared_ptr;
The use of *this can lead to memory management problems and possible dangling pointers (or wild pointers, which do not point to appropriate locations);
The use of *this is only appropriate for raw pointers and references.
Examples
Let’s say you have this code that adds and increments members of a class, as we saw in this video:
Note that the Vector2 class has a member function: increment which is a reference to itself and returns a *this!
Translating this code to use std::enable_shared_from_this, it would look like this:
Note that we inherited publicly: std::enable_shared_from_this and the type of increment is now std::shared_ptr and returns: shared_from_this().
From this code we have automatic reference management and we can even count them, example: