4

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)

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185

1 Answers1

10
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.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • So, if you have a shared pointer to it, why would you want to use shared_from_this(), just pass around the shared_pointer? I'm missing the point... – Yochai Timmer May 17 '11 at 12:41
  • 3
    @YochaiTimmer: Yes, that's usually a better approach. `shared_from_this()` just allows you to cope with situations where you have to pass a raw pointer through an interface and wish to retrieve a shared pointer that co-owns it, providing that you _know_ that the object is already owned by a shared pointer. – CB Bailey May 17 '11 at 12:46
  • 1
    enable_shared_from_this creates a local member weak_ptr that watches "this" .... So, if it already watches "this" (from construction) why wouldn't you be able to create a shared_ptr from it ? – Yochai Timmer May 17 '11 at 15:27
  • I'm not sure I understand your question, are you asking about a specific implementation of `std::enable_shared_from_this` ? – CB Bailey May 17 '11 at 15:30
  • Never-mind thanks... boost documentation: "There must exist at least one shared_ptr instance p that owns t." – Yochai Timmer May 17 '11 at 15:54