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

c++, shared-ptr

Solution

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.

Problem

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; } ```

Original source