unique_ptr 的动态转换

2021-12-31 00:00:00 casting c++ c++11 unique-ptr smart-pointers

和 Boost 一样,C++11 提供了一些用于转换 shared_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

然而,我想知道为什么 unique_ptr 没有等效函数.

I am wondering, however, why there are no equivalents functions for 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 中存在的功能等效的功能?

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?

推荐答案

您引用的每个函数都会对指针进行复制.由于您无法复制 unique_ptr,因此为其提供这些功能是没有意义的.

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.

相关文章