7

ペアからunique_ptrを返すことができないのはなぜですか?ペアから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 

私は、エラーメッセージ

+1

'std :: unique_ptr'は移動のみです。 – chris

+0

これはどのように移動できないのですか? – dspyz

答えて

9

std::unique_ptrは、コピーコンストラクタ、および方法はありません理解していません(ローカルオブジェクトのメンバーとして)それを返している場合、自動移動には適格ではありません。この場合、手動で移動を指定する必要があります。

return std::move(p.first); 
+0

自動移転の対象は何ですか? – dspyz

+1

@dspyz:参照を調べるのに数分を要しますが、リターン値の最適化のための条件と同じ条件です。 –

+6

@dspyz:12.8パラグラフ31と32をチェックしてください:http://isocpp.org/files/papers/N3797.pdf –

関連する問題