正如Boost中的情况一样,C++ 11提供了一些用于转换的函数shared_ptr:
std::static_pointer_cast
std::dynamic_pointer_cast
std::const_pointer_cast
Run Code Online (Sandbox Code Playgroud)
但是,我想知道为什么没有等效功能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));
Run Code Online (Sandbox Code Playgroud)
是否有任何理由不鼓励这种使用模式,因此,shared_ptr没有提供与现有模式相同的功能unique_ptr …