Shared_ptr从unique_ptr转换为数组
shared_ptr from unique_ptr to an array
Scott Meyers在他的书Effective Modern c++ 中提到,不鼓励对数组使用shared_ptr
,因为当转换为基类指针时,它会在类型系统中产生"漏洞"。
然而,可以通过以下方式从unique_ptr<T[]>
生成shared_ptr<T>
std::shared_ptr<D> pDerived = std::shared_ptr<D>(std::make_unique<D[]>(3)); // Create an array of 3 D's
上面的代码有潜在的危险吗?如果pDerived
稍后被复制到pBase
中,是否有陷阱?
std::shared_ptr<B> pBase = pDerived; // B is the base class for D
上面的代码有潜在的危险吗?
这取决于你怎么用它。
它不会泄漏资源,因为使用delete[]
的default_delete<D[]>
将从unique_ptr
复制并存储在shared_ptr
中(如shared_ptr
如果将
pDerived
复制到pBase
中,是否存在缺陷?
是的,如果你做了像pBase.get()[1]
这样的操作那么如果sizeof(B) != sizeof(D)
Library Fundamentals TS中的std::experimental::shared_ptr
正确支持数组(由N3939提出)。
在TS版本中,shared_ptr<D>
不允许从unique_ptr<D[]>
构建,但shared_ptr<D[]>
允许。shared_ptr<D[]>
不能转换为shared_ptr<B[]>
,以避免您提到的安全问题。
对数组的支持可能会在未来的c++标准中纳入std::shared_ptr
,但目前仅在TS中。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 唯一/共享 ptr 用于在数组超出范围后自动删除阵列
- 如何将函数 ptr 分配给函数 ptrs 数组(Arduino C++)
- 如何删除带有 int ptr 指向它的数组
- 动态2d数组:int(*ptr)[4]=new int[7][4];
- 有没有办法在数组上遍历shared_或任何"smart" ptr?
- 从数组的共享ptr访问共享ptr
- 分配const char *ptr数组参数?c++
- 按字母顺序排列字符串数组(甚至是*ptr)
- 使用ptr-to-ptr数组
- c++类的析构函数包含ptr到对象的数组