Probably a hoax, but I can't find it.
After two days of nunchucking my keyboard, I found that overloading the equals ( operator=
) operator seems to break std::sort
. Maybe I'm overloading operator=
wrong? This is my 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;
}
If I run this code as is, each person is not sorted by age. PrintPeople
is output in the same order that I initialized people
in. However, if I comment on the entire function Person operator=
, then it people
prints in ascending order of age. I see the same behavior, whether I call std::sort(people.begin(), people.end());
or std::sort(people.begin(), people.end(), Person::SortPeople);
, and I see the same behavior, whether I use g++
version 7.2.1 or clang++
version 4.0.1. I am running Fedora 27.
- , operator=
std::sort
?
-Wall -Wextra -Wconversion -std=c++11
, .