排序unique_ptrs列表

Zac*_*ach 2 c++ smart-pointers

以下代码将无法编译:

bool ptrLess(unique_ptr<int> ptr1, unique_ptr<int> ptr2)
{
   return *ptr1 < *ptr2;
}

int main()
{
   unique_ptr<int> ptr1(new int(3));
   unique_ptr<int> ptr2(new int(2));
   unique_ptr<int> ptr3(new int(5));
   list<unique_ptr<int>> list;

   list.push_back(ptr1);
   list.push_back(ptr2);
   list.push_back(ptr3);

   list.sort(ptrLess);

   for (auto &element : list) {
      cout << *element;
   }

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我假设这是因为unique_ptr删除了复制构造函数.我得到一个错误:

错误C2280:'std :: unique_ptr> :: unique_ptr(const std :: unique_ptr <_Ty,std :: default_delete <_Ty >>&)':尝试引用已删除的函数

有没有办法对列表进行排序unique_ptr,可能是通过使用移动构造函数来代替?

joe*_*hip 5

您应该使用const ref - 毕竟您不想修改这些指针:

bool ptrLess(const unique_ptr<int>& ptr1, const unique_ptr<int>& ptr2)
Run Code Online (Sandbox Code Playgroud)

如果你的list模板是std::list,那么传递参数作为r值引用将不起作用 - list::sort将不得不调用std::move有效重置指针.

编辑

至于列表的其余代码:std::list有一个方便的方法叫emplace_back(和emplace_front),它允许你就地构造和追加一个元素:

your_list.emplace_back(new int(2));
Run Code Online (Sandbox Code Playgroud)