Alexander
Alexander

Reputation: 1329

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

Upvotes: 8

Views: 3441

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63755

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.

Upvotes: 23

John Zwinck
John Zwinck

Reputation: 249133

This will "work" (but see below):

activeInstance.reset(this);

The problem is, what does it mean? When activeInstance goes out of scope, this will be deleted. That may not be what you want. You should also read about enable_shared_from_this, which would allow you to say:

activeInstance = shared_from_this();

Another option is to use a "null deleter", that is, specify a deleter function which does nothing:

void NoDelete(void*) {}

activeInstance.reset(this, NoDelete);

In many cases this will be a safe and correct solution, assuming that this will be deleted by some other method elsewhere, and not before the last dereference of activeInstance.

Upvotes: 3

Related Questions