Std :: enable_shared_from_this ... Does the new shared_ptr know to accept shared_from_this ()?

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

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

};

I know that I have to create shared pointers from an instance like this:

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

The question is whether the weak_ptr object will be implicitly accepted if I do something like this:

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

Or will it just create a separate shared pointer counter? (what I suspect)

+3
source share
1 answer
Blah* b = new Blah();
std::shared_ptr<Blah> good(b->shared_from_this()); // bad, *b is not yet owned

This is not true. To work shared_from_this, it bmust already belong to at least one shared_ptr. You should 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, this is simpler:

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

There is nothing inside:

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

new B() b, b .

+9

All Articles