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)
This is incorrect. For
shared_from_thisto work,bmust already be owned by at least oneshared_ptr. You must use:Of course, in this trivial example it is easier to use:
There is nothing intrinsically wrong with:
Because
new B()creates a newBthere can be no other separate shared pointer count in existence for the newly createdBobject.