I have a method on a class to make a particular instance an "active" instance:
void makeActive() { activeInstance = this; }
However it doesn't work since activeInstance
has type std::shared_ptr< ClassName >
. How can I cast this
to std::shared_ptr<ClassName>
?
If your object is already owned by a shared_ptr
, you can produce another shared_ptr
by having your object inherit from std::enable_shared_from_this
This code will then work:
void makeActive() { activeInstance = shared_from_this(); }
If your object is not already owned by a shared_ptr
, then you sure as heck don't want to create one in makeActive()
since a shared_ptr
will try to delete your object when the last one is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With