为什么“解构函数”调用比“构造函数”调用多?

时间:2019-07-07 01:47:37

标签: c++ stl

我正在尝试使用stl学习C ++,我发现deconstruct调用比construct调用多,我想知道我是否错过了任何内容。

代码如下:

#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;
    }
}

这是输出:

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已被解构三次,但只被创建了一次。

有什么解释吗?

谢谢。

1 个答案:

答案 0 :(得分:4)

别忘了创建副本构造函数。

Person(const Person &p): name{p.name} {
    cout << "created " << this->name << endl;
}