If you want a class to have a shared_ptr
to itself (or, rather, its this
pointer), there is an alternative way to accomplish this instead of your proposed solution via std::enable_shared_from_this
. For example:
class Player : public std::enable_shared_from_this<Player> {
//... definition
std::shared_ptr<Player> GetPtr() { return shared_from_this(); }
};
By inheriting this class, it allows you to get a shared_ptr
to the this
pointer by calling the inherited member function shared_from_this
in any of the class' member functions (although this function would not be available in the constructor). One limitation of this is that the object would need to have been stored in a shared_ptr
previously or this will caused undefined behavior (before C++17) or throw std::bad_weak_ptr
(C++17 and after).
In any case, this will likely give you the functionality you would like and avoid having to pass a shared_ptr
to itself via the constructor.