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?
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.
If the following is possible to do
Base* ptr_base = new Derived()
Then the following should also be true
std::shared_ptr<Derived> ptr_derived = std::make_shared<Derived>();
std::shared_ptr<Base> ptr_base = ptr_derived;
// The shared pointer count is 2 as logically there are 2 handles to
// to the same memory object.
After this the base shared pointer can be used for run-time polymorphism as we used to use raw pointers for the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With