Shared_ptr从unique_ptr转换为数组

shared_ptr from unique_ptr to an array

本文关键字:ptr 数组 转换 Shared unique      更新时间:2023-10-16

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从unique_ptr<T[]祝辞)。>

如果将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中。