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 的动态转换
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
