【问题标题】:shared_ptr from unique_ptr to an arrayshared_ptr 从 unique_ptr 到数组
【发布时间】:2015-09-09 15:15:00
【问题描述】:

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

【问题讨论】:

标签: c++ c++11


【解决方案1】:

上面的代码有潜在危险吗?

这取决于你用它做什么。

它不会泄漏资源,因为使用delete[]default_delete&lt;D[]&gt; 将从unique_ptr 复制并存储在shared_ptr 中(如Initialization of shared_ptr<T> from unique_ptr<T[]> 所述)。

如果稍后将pDerived 复制到pBase 中,是否存在陷阱?

是的,如果您执行 pBase.get()[1] 之类的操作,那么如果 sizeof(B) != sizeof(D) 则这不是指向第二个元素的有效指针

来自Library Fundamentals TSstd::experimental::shared_ptr 正确支持数组(如N3939 所建议的那样)。

对于 TS 中的版本,shared_ptr&lt;D&gt; 不允许从 unique_ptr&lt;D[]&gt; 构造,但 shared_ptr&lt;D[]&gt; 可以。 shared_ptr&lt;D[]&gt;不能转换成shared_ptr&lt;B[]&gt;,避免你提到的安全问题。

在未来的 C++ 标准中,对数组的支持可能会使其成为 std::shared_ptr,但目前仅在 TS 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-09
    • 2015-08-10
    • 2021-08-28
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多