如何对没有复制构造函数的对象使用std::sort

How can I use std::sort with objects that have no copy constructor?

本文关键字:对象 std sort 构造函数 复制      更新时间:2023-10-16

我试图对包含不可复制可构造或默认可构造(但可移动可构造)对象的向量进行排序,但我遇到了编译器无法为swap找到有效函数的错误。我以为有一个move构造函数就足够了。我在这里错过了什么?

class MyType {
public:
    MyType(bool a) {}
    MyType(const MyType& that) = delete;
    MyType(MyType&& that) = default;
};
int main(void) {
    vector<MyType> v;
    v.emplace_back(true);
    sort(v.begin(), v.end(), [](MyType const& l, MyType const& r) {
        return true;
    });
}

您需要显式定义一个移动赋值运算符,因为这也是std::sort尝试的(不仅仅是移动构造)。请注意,由于存在用户提供的复制构造函数以及用户提供的移动构造函数(即使它们是delete-ed),因此禁止编译器生成移动赋值运算符。示例:

#include <vector>
#include <algorithm>
class MyType {
public:
    MyType(bool a) {}
    MyType(const MyType& that) = delete;
    MyType(MyType&& that) = default;
    MyType& operator=(MyType&&) = default; // need this, adapt to your own need
};
int main(void) {
    std::vector<MyType> v;
    v.emplace_back(true);
    std::sort(v.begin(), v.end(), [](MyType const& l, MyType const& r) {
        return true;
    });
}

在Coliru上直播

Howard Hinnant(C++11中移动语义的主要贡献者)的幻灯片非常有用,还有Scott Meyers的Effective Modern C++中的项目17:理解特殊成员函数生成