Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::shared_ptr upcasting to base class - best method?

Tags:

c++

shared-ptr

Which conversion is better, and what is the difference?

class Base
{};

class Derived : public Base, public std::enable_shared_from_this<Derived>
{};

int main(int argc, const char * argv[])
{
    std::shared_ptr<Base> ptr1 = std::dynamic_pointer_cast<Base>(std::shared_ptr<Derived>(new Derived())); // version 1
    std::shared_ptr<Base> ptr2 = std::shared_ptr<Derived>(new Derived()); // version 2
    return 0;
}
like image 407
Piotr Wach Avatar asked Jan 09 '14 11:01

Piotr Wach


People also ask

Why downcasting is not safe in C++?

Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.

What does Shared_ptr get () do?

shared_ptr::getReturns a pointer to the managed object.

Is used for downcasting base class pointers?

A dynamic cast expression is used to cast a base class pointer to a derived class pointer. This is referred to as downcasting.

What is down casting in C++?

The Downcasting is an opposite process to the upcasting, which converts the base class's pointer or reference to the derived class's pointer or reference. It manually cast the base class's object to the derived class's object, so we must specify the explicit typecast.


1 Answers

As in other use cases of shared_ptr, you should prefer using make_shared instead of constructing the shared_ptr manually:

std::shared_ptr<Base> ptr2 = std::make_shared<Derived>();

This is essentially your version 2, plus the various benefits of make_shared.

Version 1 does a bunch of unnecessary stuff: First you construct a temporary shared_ptr<Derived>, then you dynamic_cast its contents to a base class pointer (while a static_cast would be sufficient here) and then you store that pointer in a different shared_ptr<Base>. So you have a lot of unnecessary runtime operations, but no benefits regarding type safety over Version 2.

like image 54
ComicSansMS Avatar answered Oct 06 '22 00:10

ComicSansMS