Dynamiczny casting dla unique_ptr
Podobnie jak w przypadku Boosta, C ++ 11 udostępnia pewne funkcje do rzutowaniashared_ptr
:
std::static_pointer_cast
std::dynamic_pointer_cast
std::const_pointer_cast
Zastanawiam się jednak, dlaczego nie istnieją funkcje równoważneunique_ptr
.
Rozważmy następujący prosty przykład:
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));
Czy jest jakiś powód, dla którego ten wzorzec użycia jest zniechęcony, a zatem funkcje równoważne do tych obecnych wshared_ptr
nie są przewidzianeunique_ptr
?