The Ranges Library in C++20
The Ranges Library in C++20
October 4, 2022
How to automatize a job in Linux System?
How to automatize a job in Linux System?
October 18, 2022

October 11, 2022

C++11’s shared_from_this

Dependency Injections and complicated OOP patterns may result into conflicts of lifetime/ownership relationships in a spaghetti code. Enclosing the ownership of an object in a smart pointer may look like an appropriate solution to this; but may result into utilizing dependency injections in a hierarchical fashion and unnecessary copies and destructions. shared_from_this prevents double free operations and provides a better solution for the "this" instance to be kept alive.

#include <iostream>
#include <memory>
class ShareMe: public
               std::enable_shared_from_this<ShareMe>
{
   public:
     std::shared_ptr<ShareMe> getShared () {
       return shared_from_this();
     }
};
C++11’s shared_from_this
This website uses cookies to improve your experience. By using this website you agree to our Data Privacy Statement
Read more