7

次のコードは C++11 に従ってコンパイル エラーを生成することになっていますか (そうである場合、その理由は?)、それとも VC11 の問題ですか?

#include <vector>
#include <list>
#include <memory>
struct A
{
    std::vector<std::unique_ptr<int>> v;
};
int main()
{
    std::list<A> l;
    l.sort([](const A& a1, const A& a2){ return true; });
}

Visual C++ 2012 では、次のコンパイル エラーが発生します。

1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(606): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
1>          with
1>          [
1>              _Ty=int
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\memory(1447) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr'
1>          with
1>          [
1>              _Ty=int
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(605) : while compiling class template member function 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)'
1>          with
1>          [
1>              _Ty=std::unique_ptr<int>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(751) : see reference to function template instantiation 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)' being compiled
1>          with
1>          [
1>              _Ty=std::unique_ptr<int>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\type_traits(743) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=std::unique_ptr<int>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector(655) : see reference to class template instantiation 'std::is_empty<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=std::allocator<std::unique_ptr<int>>
1>          ]
1>          d:\test2\test2.cpp(213) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=std::unique_ptr<int>
1>          ]
4

3 に答える 3

4

これは「VC の問題」ですが、Visual Studio を誤用しているためです。

VC++ は右辺値参照を実装していますが、コンパイラによって生成されたムーブ コンストラクター/代入演算子は実装していません。つまり、型を移動可能にしたい場合は、自分で作成する必要があります。

Aは移動可能なタイプではないため、さまざまなstd::list関数がそれらをコピーしようとします。vectorまた、 ofをコピーしようとすると失敗しますunique_ptr。したがって、コンパイラエラー。

VC++ でムーブ対応オブジェクトが必要な場合は、ムーブ コンストラクター/代入を自分で作成する必要があります。

于 2013-05-05T15:26:01.203 に答える