1

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.

BlueDolphin
  • 9,765
  • 20
  • 59
  • 74
  • See [this answer](https://stackoverflow.com/questions/56799469/why-is-emplace-back-behaving-like-this/56799500#56799500) and the corresponding question. – milleniumbug Jul 07 '19 at 01:57

1 Answers1

4

Don't forget to create a copy constructor.

Person(const Person &p): name{p.name} {
    cout << "created " << this->name << endl;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578