c++ - 为什么我不能从一对中返回一个 unique_ptr?

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

为什么我不能从一对中返回一个 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 没有复制构造函数,并且您返回它的方式(作为本地对象的成员)不符合自动移动的条件。在这种情况下,您需要手动指定移动。

return std::move(p.first);

关于c++ - 为什么我不能从一对中返回一个 unique_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20650997/

相关文章:

c++ - 带break openmp的并行If-else循环

c++ typeid 使用 get() 和 * 为相同的 unique_ptr 返回不同的值

rvalue-reference - 初始化列表中的右值引用用法

c++ - 如何使用条件预处理器排除以下代码

c++ - std::ifstream::operator>> 无法将 0xABCD 转换为短字符?

c++ - 单生产者多消费者循环缓冲区

c++ - 不能 push_back vector 中的 unique_ptr

c++ - 带有工厂设计尝试的段错误 unique_ptr

c++ - 完美转发到作为参数接收的 lambda

c++ - 与 move 构造函数混淆 : unable to call move constructor