C++11提供了一些用于强制转换shared_ptr
的函数,就像在Boost中一样:
std::static_pointer_cast
std::dynamic_pointer_cast
std::const_pointer_cast
然而,我想知道为什么没有类似于unique_ptr
的等效函数。
考虑以下简单的示例:
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));
这种使用模式为什么被反对,因此,unique_ptr
中没有提供与shared_ptr
中存在的等效函数?
pA
指向的对象不能转换为类型B
(即dynamic_cast<B>(pA.get())
失败),那么您希望对该对象采取什么操作?pA
应该保持所有权吗?还是应该被销毁? - cdhowiedynamic_cast
失败,"常识" 会建议中止转换,而不修改原始指针。这实际上是 cdhowie 答案中的行为。 - betabandido