Search code examples
c++castingc++11smart-pointersunique-ptr

Dynamic casting for unique_ptr


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

std::static_pointer_cast
std::dynamic_pointer_cast
std::const_pointer_cast

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

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 shared_ptr are not provided for unique_ptr?


Solution

  • 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.