In principle it is allowed to derive from STL classes, see here and here. However, you have to be aware that you should not work with a pointer to the base class -- i.e. a std::shared_ptr<myotherclass>*
in this case.
So this and variants thereof should be forbidden:
std::shared_ptr<myotherclass>* ptr = new myclass(/* ... */);
... but agreed, that looks a bit synthetic.
Why is it forbidden? Because the STL classes do not have a virtual destructor. So when you want to delete
your allocated class, the derived part remains. This in turn invokes undefined behaviour and possibly creates a memory leak -- even if you do not have some allocations in your derived class.
In order to do so, one possibility is to derive privately from shared_ptr
:
class myclass : private std::shared_ptr<myotherclass> {};
^^^^^^^
This however might bring in problems with the binary compatibility, see the comments to this answer.
On the hand, even though the former is allowed, you can go on less error-prone and either use composition, where you make the shared_ptr
a member of myclass
and expose the required functionality (with the drawback that you sometimes have to expose a lot). Or you can set up a standalone function which does what you want ... I know you knew that ;-)