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();
}
};