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;
}
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.
shared_ptr::getReturns a pointer to the managed object.
A dynamic cast expression is used to cast a base class pointer to a derived class pointer. This is referred to as downcasting.
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.
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.
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