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 的动态转换
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01