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

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

我正在尝试对包含不可复制构造或默认可构造(但可移动构造)的对象的向量进行排序,但我收到关于编译器无法为 [=12= 找到有效函数的错误].我认为有一个移动构造函数就足够了。我在这里错过了什么?

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;
    });
}

您需要通过 user-provided 复制构造函数的存在以及 user-provided 移动构造函数的存在来显式定义 move assignment operator, as this is what std::sort also tries (not just move construction). Note that the compiler-generation of a move assignment operator is prohibited(即使它们是 delete-编)。示例:

#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;
    });
}

Live on Coliru

Scott Meyers 的 slides by Howard Hinnant (the main contributor to move semantics in C++11) are super useful, as well as Item 17: Understand special member function generation from Effective Modern C++