c++ - 对持有 unique_ptr vector 的对象列表进行排序

标签 c++ list c++11 vector unique-ptr

根据 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>          ]

最佳答案

这是“VC 的问题”,但这只是因为您滥用了 Visual Studio。

VC++ 实现右值引用,但它实现编译器生成的移动构造函数/赋值运算符。这意味着,如果您希望一个类型是可移动的,您必须自己编写一个。

A 不是可移动类型,因此各种 std::list 函数将尝试复制它们。当他们尝试复制 unique_ptrvector 时,他们会失败。因此编译器错误。

如果你想要在 VC++ 中移动感知对象,你必须自己为它们编写移动构造函数/赋值。

关于c++ - 对持有 unique_ptr vector 的对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385482/

相关文章:

c++ - 为什么我在赋值后得到不同的指针值?

java - 将列表的元素添加到另一个列表后清除列表

c++11 全局初始化顺序和thread_local

templates - 通过函数指针函数将lambda作为模板参数传递给模板

c++ - 在mfc中嵌入Window Media Player

c++从文本文件帮助输入

c++ - 在 arm neon 中高效地重新洗牌和组合 16 个 3 位数字

Python .pop() 全局更改本地列表?

java - 如何区分同一个整数对象?

c++ - g++ - 为什么在使用 std::thread 时必须传递 "-pthread"选项?