betabandido betabandido - 1 year ago 190
C++ Question

Dynamic casting for unique_ptr

As it was the case in Boost, C++11 provides some functions for casting



I am wondering, however, why there are no equivalents functions for

Consider the following simple example:

class A { virtual ~A(); ... }
class B : public A { ... }

unique_ptr<A> pA(new B(...));

unique_ptr<A> qA = std::move(pA); // This is legal since there is no casting
unique_ptr<B> pB = std::move(pA); // This is not legal

// I would like to do something like:
// (Of course, it is not valid, but that would be the idea)
unique_ptr<B> pB = std::move(std::dynamic_pointer_cast<B>(pA));

Is there any reason why this usage pattern is discouraged, and thus, equivalent functions to the ones present in
are not provided for

Answer Source

The functions you refer to each make a copy of the pointer. Since you can't make a copy of a unique_ptr it doesn't make sense to provide those functions for it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download