I have a vector of Persons. At the time i thought it would be a good idea to give every person a unique id. And so i did:
class Person {
Person::Person(): id(currentID++){
}
const int id;
}
After a while i wanted to build a vector of persons and so i learned that i'd have to provide a few more functions:
An element of vector must be:
Copyable, i.e. have a constructor compatible with T(const T&) Assignable, i.e. have an operator= compatible with operator=(const T&). Default-constructible, i.e. have a constructor compatible with T().
And so i did my best and came up with
Person::Person(const Person& other): id(other.id) {
}
Person& Person::operator=(const Person& other)
}
Everything seemed to be working splendidly.
But one day i tried to erase an element from my vector just like i learned
vector<Person> persons;
persons.push_back(Person()); //id 0
persons.push_back(Person()); //id 1
persons.push_back(Person()); //id 2
vector<Person>::iterator it;
for(it = persons.begin() ; it != persons.end() ; ) {
if(it->getID() == 1) {
it = persons.erase(it);
} else {
it++;
}
}
//persons.size() == 1
I checked the debugger and saw that erase uses the operator=
to move the elements after the call to erase. Obviously id wasn't changed and so i deleted every element after id 1 in my vector.
Why is that the case? I always thought vector erase just would move the pointer from element 0 to 2 to drop element 1.
How should i deal with my const id
? Should i include it in operator=
?
I read about a move operator in C+11 (which i use), would vector use this special operator if i provide it?