【问题标题】:Why can't I make a unique pointer to an array, when I can make a shared pointer?当我可以创建共享指针时,为什么我不能创建指向数组的唯一指针?
【发布时间】:2018-12-28 19:44:15
【问题描述】:

以下内容无效:

#include <memory>
#include <iostream>
typedef double zip[10];

int main()
{
    std::unique_ptr<zip> s = std::make_unique<zip>();
    (*s)[0] = 2.0;
    std::cout << (*s)[0] << std::endl;
    return 0;
}

但以下是完全有效的:

int main()
{
    std::shared_ptr<zip> s = std::make_shared<zip>();
    (*s)[0] = 2.0;
    std::cout << (*s)[0] << std::endl;
    return 0;
}

为什么会出现差异?我错过了什么?

【问题讨论】:

  • 不是你问的,但是unique_ptrdouble[10] 的正确语法是auto s = std::make_unique&lt;double[]&gt;(10);
  • 您的第一个代码也适用于typedef std::array&lt;double, 10&gt; zip;

标签: c++ c++17


【解决方案1】:

不同之处在于shared_ptr 可能指向也可能不指向数组。任何特定的shared_ptr&lt;T&gt; 实例都可能指向单个TT 的数组。

相比之下,unique_ptr&lt;T&gt; 始终指向单个 T,而 unique_ptr&lt;T[]&gt; 指向 T 的数组。它直接在类型本身中编码。所以存储数组的版本有一个适当的operator[] 重载,而另一个没有。

还需要注意的是,shared_ptr::operator[] 是 C++17 的补充,而 unique_ptr&lt;T[]&gt;::operator[] 一直存在。

【讨论】:

  • 如果是17,那么第二个例子无效。
【解决方案2】:

因为已知边界数组上的make_unique 是不允许的。看 Why is `make_unique<T[N]>` disallowed?https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique

【讨论】:

  • 您的意思是“unknown”,而不是“known”。
  • 不,真的“知道”。 make_unique&lt;T[]&gt; 可以,但make_unique&lt;T[n]&gt; 不行。请参阅提到的 StackOverflow 问题。
  • @AdrianTam:OP 询问为什么您不能在 unique_ptr&lt;T&gt; 上使用 operator[]。这与make_unique 无关。
猜你喜欢
  • 2021-10-17
  • 2018-11-12
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
  • 2023-03-12
  • 2010-11-06
相关资源
最近更新 更多