unique_ptr 的动态转换

Dynamic casting for unique_ptr(unique_ptr 的动态转换)

本文介绍了unique_ptr 的动态转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于unique_ptr 的动态转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:unique_ptr 的动态转换

基础教程推荐