is there a way to use enable_shard_from_this
as a has-a relationship instead of an is-a relationship?
No.
enable_shared_from_this
is supposed to be used as a base class, so mindlessly applying a guideline meant for other situations doesn't work in this case.
Even if there was a good reason to want to do this (and there isn't) it wouldn't work. The magic that causes the enable_shared_from_this
base to share ownership with the shared_ptr
that owns the derived object works by checking for inheritance.
enable_shared_from_this
doesn't model an IS-A relationship anyway, because it has no interface defined in terms of virtual functions. IS-A means a derived type that extends a base interface, but that isn't the case here. A Good
IS-NOT-A enable_shared_from_this<Good>
.
i.e. using inheritance does not always imply an IS-A relationship.
- enable_shared_from_this doesn't have a virtual destructor
A virtual destructor is irrelevant unless you plan to delete the object through a pointer to the enable_shared_from_this
base class, which would be insane. There is no reason to ever pass around a Good
as a pointer to the enable_shared_from_this<Good>
base class, and still less reason to ever use delete
on that base pointer (usually the type would be stored in a shared_ptr<Good>
as soon as it's created, so you would never use delete
at all).
enable_shared_from_this
is a mixin type, not an abstract base. It provides the shared_from_this
(and soon weak_from_this
) member, that's all. You are not supposed to use it as an abstract base or an interface type, nor use the base type to access polymorphic behaviour of the derived type. The fact it has no virtual functions at all, not just no virtual destructor, should tell you that.
Furthermore, as n.m. commented above, the destructor is protected, so you can't delete it via the base class even if you tried (a protected destructor is the idiomatic way of preventing that type of misuse of mixin classes intended to be non-polymorphic base classes).
- The
enable_shared_from_this
destructor destroys *this
, meaning it must always be the last destructor called
Huh? Not sure what you mean, but it isn't responsible for destroying anything except itself and its own data member.
- Inheritance from two classes that both inherit from
enable_shared_from_this
can become a bit of a sticking point
It should work OK (although you might not get the magic ownership sharing if there isn't a single unambiguous base class that is a specialization of enable_shared_from_this
). The GCC standard library had a bug (now fixed) where it fails to compile, rather than just fail to share ownership, but that's not a problem with enable_shared_from_this
.