【问题标题】:Why can't I return a unique_ptr from a pair?为什么我不能从一对中返回 unique_ptr?
【发布时间】:2013-12-18 06:22:20
【问题描述】:

为什么我不能从一对中返回 unique_ptr?

#include <iostream>
#include <memory>
#include <utility>

using namespace std;

unique_ptr<int> get_value() {
    pair<unique_ptr<int>, int> p(unique_ptr<int>(new int(3)), 4);
    return p.first;
}

int main(void) {
    cout << *get_value() << endl;
    return 0;
}

当我尝试用 g++ 4.6 编译它时,我得到:

../main.cpp: In function ‘std::unique_ptr<int> get_value()’:
../main.cpp:9:11: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int, _Dp = std::default_delete<int>, std::unique_ptr<_Tp, _Dp> = std::unique_ptr<int>]’
/usr/include/c++/4.6/bits/unique_ptr.h:256:7: error: declared here
make: *** [main.o] Error 1

我不明白错误信息

【问题讨论】:

  • std::unique_ptr 只能移动。
  • 这不是只能移动的吗?

标签: c++ unique-ptr rvalue-reference std-pair perfect-forwarding


【解决方案1】:

std::unique_ptr 没有复制构造函数,并且您返回它的方式(作为本地对象的成员)不符合自动移动的条件。在这种情况下,您需要手动指定移动。

return std::move(p.first);

【讨论】:

  • 我怎么知道什么符合自动移动的条件?
  • @dspyz:请给我一分钟时间来查找参考,但它符合返回值优化的条件。
  • @dspyz:检查 12.8 第 31 和 32 段:isocpp.org/files/papers/N3797.pdf
  • @dspyz,为了扩展,如果你刚刚做了std::unique_ptr&lt;int&gt; p(new int(3)); return p;,它将符合条件。
猜你喜欢
  • 2012-08-20
  • 1970-01-01
  • 2011-03-18
  • 2011-06-28
  • 1970-01-01
  • 2013-05-09
  • 2019-03-03
  • 2020-10-24
  • 2014-04-20
相关资源
最近更新 更多