Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
Stéphane Avatar asked Dec 29 '25 20:12

Stéphane


2 Answers

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.

like image 193
hgiesel Avatar answered Dec 31 '25 10:12

hgiesel


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.

like image 25
Abdus Khazi Avatar answered Dec 31 '25 12:12

Abdus Khazi