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

淺唱寂寞╮ 提交于 2019-12-09 17:23:45

问题


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;
}

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

I don't understand the error message


回答1:


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);


来源:https://stackoverflow.com/questions/20650997/why-cant-i-return-a-unique-ptr-from-a-pair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!