问题
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