对包含unique_ptr向量的对象列表进行排序

Pow*_*mer 7 c++ list vector unique-ptr c++11

以下代码是否应该根据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; });
}
Run Code Online (Sandbox Code Playgroud)

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>          ]
Run Code Online (Sandbox Code Playgroud)

Pow*_*mer 1

这是 Visual C++ 2012 的一个问题(Microsoft 在 Connect 上承认:对持有 unique_ptr 向量的对象列表进行排序的 C++ 代码中出现编译错误),并且已在 Visual C++ 2013 中修复。

另外,我想指出一个问题与 Visual C++ 不会隐式生成移动构造函数这一事实无关。如果您显式删除结构体 A 中的所有复制和移动构造函数(是的,这将使得不可能将类型 A 的对象插入到列表中,但这不是重点),在我的原始示例中,代码仍然不应该复制或移动任何构造函数。对象并因此产生编译错误:

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