加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:27:28 所属栏目:百科 来源:网络整理
导读:我试图排序一个包含不可复制的或不可构造的对象(但是是可移植的)的向量,但我收到有关编译器无法找到有效的交换函数的错误.我认为有一个移动构造函数就够了.我在这里缺少什么? class MyType {public: MyType(bool a) {} MyType(const MyType that) = delete;
我试图排序一个包含不可复制的或不可构造的对象(但是是可移植的)的向量,但我收到有关编译器无法找到有效的交换函数的错误.我认为有一个移动构造函数就够了.我在这里缺少什么?
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;
    });
}

解决方法

您需要明确定义一个 move assignment operator,因为这是 std::sort也尝试(不只是移动构造).请注意,编译器通过存在用户提供的复制构造函数以及存在用户提供的移动构造函数(即使它们被删除)来生成移动赋值运算符 is prohibited.例:
#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(),MyType const& r) {
        return true;
    });
}

Live on Coliru

slides Howard Hinnant(C 11中移动语义的主要贡献者)超级有用,以及第17项:了解Scott Meyers从Effective Modern C++开始的特殊成员函数生成.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读