Yochai Timmer
Yochai Timmer

Reputation: 49269

std::enable_shared_from_this ... Does a new shared_ptr know to take shared_from_this()?

I have a class that derives from enable_shared_from_this ... (Recently been added to std from Boost)

class Blah : public std::enable_shared_from_this<Blah>
{

};

I know I should create shared pointers from an instance like this:

Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this());

Question is, will it take the object's weak_ptr implicitly if I do something like this:

std::shared_ptr<Blah> bad(new Blah());

Or will it just create a seperate shared pointer counter ? (which i suspect)

Upvotes: 4

Views: 4464

Answers (1)

CB Bailey
CB Bailey

Reputation: 793369

Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this()); // bad, *b is not yet owned

This is incorrect. For shared_from_this to work, b must already be owned by at least one shared_ptr. You must use:

std::shared_ptr<Blah> b = new B();
Blah* raw = b.get();
std::shared_ptr<Blah> good(raw->shared_from_this()); // OK because *raw is owned

Of course, in this trivial example it is easier to use:

std::shared_ptr<Blah> good(b);

There is nothing intrinsically wrong with:

std::shared_ptr<Blah> bad(new Blah());

Because new B() creates a new B there can be no other separate shared pointer count in existence for the newly created B object.

Upvotes: 11

Related Questions