Search code examples
c++c++11shared-ptr

shared_ptr<Base> and objects from derived classes


Given something like this:

class Base {...};
class D1 : public Base {...};
class D2 : public Base {...};

In my code, is it legal to use std::shared_ptr<Base> to manage the lifetime and pass around objects of types D1 and D2? Or could this cause a world of pain?


Solution

  • Yes it is completely fine. Smart pointers are designed to be drop-in replacements for dump pointers.

    Of course you have to think about whether to make Base's member functions virtual, just like you would with dumb pointers.