Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between shared_dynamic_cast and dynamic_pointer_cast

Tags:

Can someone explain to me the difference between:

shared_dynamic_cast and dynamic_pointer_cast from the Boost library?

It appears to me that they may be equivalent.

like image 924
Nick Avatar asked Feb 22 '12 09:02

Nick


People also ask

What is Dynamic_pointer_cast?

dynamic_pointer_cast is used to convert std::shared_ptr type, e.g. from the pointer on a base class to a pointer on a derived class: #include <memory> struct A{ virtual ~A() = default; }; struct B: A {}; int main() { std::shared_ptr<A> pA = std::make_shared<B>(); std::shared_ptr<B> pB = std::dynamic_pointer_cast<B>(pA ...

What is static casting and dynamic casting?

Static casting is done by the compiler: it treats the result as the target type, no matter what. You do this when you're absolutely sure about the argument being of the target type. Dynamic casting is done at runtime, and thus requires runtime type information.


1 Answers

Given a shared_ptr<T>, the two functions are indeed equivalent.

The difference is that shared_dynamic_cast only works with shared_ptr<>'s, while dynamic_pointer_cast works with any kind of pointer (via overloading). This enables you to perform a dynamic cast on any pointer concept, regardless of how that pointer is actually composed:

#include <boost/pointer_cast.hpp>
#include <boost/shared_ptr.hpp>

struct foo {};
struct bar : foo { void f(){} };

template <typename Ptr>
void test(Ptr ptr)
{
    boost::dynamic_pointer_cast<bar>(ptr)->f();
}

int main()
{
    bar b;
    foo* pf = &b;

    std::shared_ptr<foo> spf(new bar());

    test(pf); // turns into dynamic_cast<bar*>(pf)->f();
    test(spf); // turns into shared_dynamic_cast<bar>(pf)->f();
}

Because dynamic_pointer_cast has the capability of shared_dynamic_cast and more, the latter function is deprecated. (Likewise in C++11, there only exists dynamic_pointer_cast.)

(The idea is the same for the other cast variants too, of course.)

like image 80
GManNickG Avatar answered Oct 03 '22 21:10

GManNickG