It's common to inherit from enable_shared_from_this
just to be able to return shared_ptr
's from member functions as the primary intention, with no intention of exposing enable_shared_from_this
API in the derived class.
Since to make use of enable_shared_from_this
one must do so through public inheritance (does the standard mandates this? what's the rationale?), this can't be achieved and enable_shared_from_this
API is forced into derived class public API.
Inherenting enable_shared_from_this
privately and making shared_ptr
a friend class do work on clang coupled with libc++, but doesn't work with stdlibc++.
Since private enable_shared_from_this
+ friend shared_ptr
(or protected inheritance) seems to cover this use case, shouldn't it be sufficient by the standard for fitting as a solution for the "shared from this" problem?
protected
, i.e.class T : protected std::enable_shared_from_this<T> { ... };
? I didn't try it myself – Hulburtprotected
). – Yakutshared_from_this
mechanism can work if the inheritance is totally private. The way it works, if I understand right, is that the control structure for theshared_ptr
(the reference count) is stored in a prefix in your class, so like, there is some data member instd::enable_shared_from_this<T>
. In order to make ashared_ptr
fromthis
, it needs to be able to static castthis
and find the ref counter. Alsostd::make_shared
need to be able to detect things like this in your type. If the inheritance is private then I guess they can't do that. Not sure.. – Hulburtstd::shared_ptr
. – Yakutstd::make_shared
andstd::weak_ptr
and other things potentially – Hulburtshared_from_this()
is not standardized as a protected member ofstd::enable_shared_from_this
. Then if you want to expose it publicly you can put ausing
declaration. That's easier than all this friend stuff. – Hulburt