简体   繁体   English

如何将std :: sort与没有复制构造函数的对象一起使用?

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

I'm trying to sort a vector containing objects that are not copy constructible or default constructible (but are move constructible), but I get errors about the compiler not being able to find a valid function for swap . 我正在尝试对包含不可复制或默认可构造的对象的向量进行排序(但是可移动构造),但是我得到错误,因为编译器无法找到有效的swap函数。 I thought that having a move constructor would be enough. 我认为拥有一个移动构造函数就足够了。 What am I missing here? 我在这里错过了什么?

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

You need to explicitly define a move assignment operator , as this is what std::sort also tries (not just move construction). 您需要显式定义移动赋值运算符 ,因为这是std::sort也尝试(不仅仅是移动构造)。 Note that the compiler-generation of a move assignment operator is prohibited by the existence of a user-provided copy constructor, as well as by the existence of a user-provided move constructor (even if they are delete -ed). 请注意,由于存在用户提供的复制构造函数,以及存在用户提供的移动构造函数(即使它们是delete -ed), 也禁止生成移动赋值运算符。 Example: 例:

#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 住在Coliru

The 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++ by Scott Meyers. Howard Hinnant (在C ++ 11中移动语义的主要贡献者)的幻灯片非常有用,以及第17项:了解 Scott Meyers的Effective Modern C ++中特殊成员函数生成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM