为什么我不能从一个对返回unique_ptr? [英] Why can't I return a unique_ptr from a pair?

查看:401
本文介绍了为什么我不能从一个对返回unique_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why can't I return a unique_ptr from a pair?

#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编译时,我得到:

When I try to compile this with g++ 4.6, I get:

../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 没有复制构造函数,本地对象的成员)不符合自动移动条件。您需要在这种情况下手动指定移动。

std::unique_ptr does not have a copy constructor, and the way in which you are returning it (as a member of a local object) does not qualify for automatic move. You need to specify the move manually in this case.

return std::move(p.first);

这篇关于为什么我不能从一个对返回unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆