【问题标题】:std::sort a class that's implemented a move constructorstd::sort 实现了移动构造函数的类
【发布时间】:2018-10-17 18:52:36
【问题描述】:

是否可以在不使用整个元素的情况下使用 std::sort ?

std::vector<std::pair<int, myclass> > unsorted_vec;
for (some_iterations) {
    unsorted_vec.emplace_back(rand(), std::move(instance_of_myclass));
}
std::sort(unsorted_vec.begin(), unsorted_vec.end(), 
          [](auto & l, auto & r) { return l.first < r.first; });

除非std::sort 行被注释掉,否则上面的代码给出了以下编译错误。

error: use of deleted function 'myclass & myclass::operator=(const myclass &)' is 
       implicitly declared as delete because 'myclass' declares a move constructor.

现在我确实为 myclass 声明了一个移动构造函数,此外,我实际上希望删除引用构造函数。我的问题是,如何对这个数组进行排序?是否可以在不触及第二部分的情况下获得对我对的第一部分的引用?

【问题讨论】:

  • 什么是myclass
  • 您是否为myclass 创建了移动赋值运算符
  • 问题不在于访问一对成员中的一个成员,而不是另一个成员。问题在于排序会移动项目,但您的对象不可移动分配。
  • @Galik myclass 是一个充满数据和 unique_ptrs 的大类。我为myclass 创建了一个 move 构造函数,但没有创建一个 move 赋值运算符

标签: c++ c++11 lambda stdvector move-semantics


【解决方案1】:

根据std::sort 上的此参考资料,您的类需要同时可移动构造可移动分配才能可排序

如果你的班级不是天生的 moveble 那么这样的事情应该可以正常工作:

class myclass
{
public:
    myclass(myclass const&) = delete; // or implement
    myclass(myclass&& other) { /* stuff to construct */ }

    myclass& operator=(myclass const&) = delete; // or implement
    myclass& operator=(myclass&& other) { /* stuff to assign */ return *this; }

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2011-11-25
    • 2015-03-16
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多