You might be better off using std::enable_shared_from_this
, which was designed for situations like this.
To use it, derive your class from it. It will store a std::weak_ptr
which will be initialised to point to the object the first time a std::shared_ptr
pointing to that object is created:
struct SomeClass : public std::enable_shared_from_this<SomeClass>
{
//...
};
If you need to make sure a std::shared_ptr
to your class always exists, you can make all of its constructors private (or protected, as applicable) and give it a public static creation function returning a std::shared_ptr
:
struct SomeClass : public std::enable_shared_from_this<SomeClass>
{
std::shared_ptr<SomeClass> create()
{ return std::make_shared<SomeClass>(); }
private:
SomeClass()
{}
};