I am trying to study C++ using stl
, I noticed that there are more deconstruct
calls than construct
calls, I am wondering whether I missed anything.
Here is the code:
#include <vector>
#include <iostream>
using namespace std;
class Person {
friend ostream &operator<<(ostream& os, const Person &p) {
os << p.name << endl;
return os;
}
string name;
public:
Person() {
cout << "created " << this->name << endl;
};
Person(string name):
name{name} {
cout << "created " << this->name << endl;
}
~Person() {
cout << "deconstructor " << this->name << endl;
}
bool operator<(const Person &rhs) const {
return this->name < rhs.name;
}
bool operator==(const Person &rhs) const {
return (this->name == rhs.name);
}
};
int main(int argc, char** argv) {
vector<Person> vec {{"test1"}, {"test2"}};
Person p {"test2"};
vector<Person>::iterator it = find(vec.begin(), vec.end(), p);
Person p2 {"test3"};
vec.insert(it, p2);
for (auto &p : vec) {
cout << p;
}
}
And this is the output:
created test1
created test2
deconstructor test2
deconstructor test1
created test2
created test3
deconstructor test2
deconstructor test1
test1
test3
test2
deconstructor test3
deconstructor test2
deconstructor test2
deconstructor test3
deconstructor test1
test1
has been deconstructed three times, but only created once.
Any explanation?
Thanks.