重载operator = break std :: sort

yan*_*ano 4 c++ assignment-operator c++11

可能是一个骗局,但我找不到它.

在敲击键盘两天之后,我发现重载equals运算符(operator=)显然会中断std::sort.也许我的输operator=错不正确?这是我的MCVE:

#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <cstdint>
#include <vector>

struct Person
{
  std::string name;
  uint32_t age;

  bool operator< (const Person& p)
  {
    return this->age < p.age;
  }

  Person operator= (const Person& p)
  {
    Person newP;
    newP.name = p.name;
    newP.age = p.age;

    return newP;
  }

  static bool SortPeople(const Person& p1, const Person& p2)
  {
    return p1.age < p2.age;
  }
};

void PrintPeople(const std::vector<Person>& people)
{
  std::cout << "============ people begin" << std::endl;
  for (const auto& pIt : people)
  {
    std::cout << "name: " << pIt.name << ", age: " << pIt.age << std::endl;
  }
  std::cout << "============ people end" << std::endl;
}

int main()
{
  std::vector<Person> people = { { "james", 12 },
                                 { "jada", 4   },
                                 { "max", 44   },
                                 { "bart", 7   }
                               };

  PrintPeople(people);


  std::sort(people.begin(), people.end());
  PrintPeople(people);  

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我按原样运行此代码,则不会根据年龄对每个人进行排序. PrintPeople打印出的相同顺序初始化我people的.不过,如果我注释掉整个Person operator=函数,然后people 得到基于年龄递增顺序打印出来.我看这种行为是否我打电话std::sort(people.begin(), people.end());或者std::sort(people.begin(), people.end(), Person::SortPeople);,我看这种行为是否我使用g++版本7.2.1或clang++4.0.1版本.我正在运行Fedora 27.

任何人都知道为什么超载operator=休息std::sort

我正在用旗帜编译,-Wall -Wextra -Wconversion -std=c++11没有警告.

son*_*yao 5

是的,你operator=错了.它应该修改*this,但你正在修改本地对象newP.

将其更改为

Person& operator= (const Person& p)
{
  name = p.name;
  age = p.age;

  return *this;
}
Run Code Online (Sandbox Code Playgroud)

std::sort通过移动它们来排序元素,它使用重载operator=Person.这就是错误的实现在std::sort这里打破的原因.

顺便说一句:当您删除实现时,自动生成的赋值运算符会为您做正确的事情.

  • @FrançoisAndrieux防止在临时对象上进行赋值,例如内置类型. (2认同)