Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast 'this' to std::shared_ptr

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>?

like image 371
Alexander Avatar asked Jan 12 '15 01:01

Alexander


1 Answers

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.

like image 145
Drew Dormann Avatar answered Oct 22 '22 20:10

Drew Dormann