Dynamic casting for 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 的动态转换
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
