The cpp reference has this example of how to use std::enable_shared_from_this
(slightly adjusted)
class Good : std::enable_shared_from_this<Good>
{
public: std::shared_ptr<Good> getptr() { return shared_from_this(); }
};
...
auto good = std::make_shared<Good>();
good->getptr();
However, this does NOT work in Visual Studio 2015 (Enterprise, Version 14.0.25123.00 Update 2), i.e. a std::bad_weak_ptr
exception is thrown.
Looking at other examples (including different ones from cpp reference or Microsoft) I noticed that they use public
inheritance instead of private
one. And using public
inheritance actually solves my problem (no std::bad_weak_ptr
anymore but a valid shared_ptr
instead).
Cpp reference does not mention that I have to publicly inherit from std::enable_shared_from_this
, so where is the error? Is Visual Studio's behavior wrong (I guess there is a visibility problem when using private
inheritance) or did cpp reference fail to mention this limitation?
PS: make_shared<good>()
or shared_ptr<Good>(new Good)
doesn't make a difference.
PSS: Both versions compile just fine, the private one just doesn't work, making this a quite nasty kind of bug.
EDIT: Changed struct
to class
. Cpp reference actually uses public inheritance in its examples. Still, no word that it has to be public. It is actually listed there, I just have to learn to read carefully. Thanks @Angew.