Stéphane
Stéphane

Reputation: 20380

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?

Upvotes: 3

Views: 3101

Answers (3)

Abdus Khazi
Abdus Khazi

Reputation: 483

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.

Upvotes: 2

Christophe
Christophe

Reputation: 73607

This is perfectly ok if your classes are designed for polymorphism.

If your classes are not polymorphic (i.e. no virtual members), this construct could require additional work (every object would be handled as if it were a Base object when you'd invoke member functions). In this case you'd better use std::shared_ptr<Base>, std::shared_ptr<D1>, std::shared_ptr<D2>... and static_pointer_cast<> when needed.

Upvotes: 1

hgiesel
hgiesel

Reputation: 5658

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.

Upvotes: 2

Related Questions