c++ - 为什么 `deconstructor` 调用比 `constructor` 调用多?

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

有什么解释吗?

谢谢。

最佳答案

不要忘记创建一个复制构造函数。

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

关于c++ - 为什么 `deconstructor` 调用比 `constructor` 调用多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918835/

相关文章:

c++ - std::list 顺序有保证吗?

c++ - STL vector 之间的自动转换

c++ - NV12 纹理在 DirectX 11.1 中不起作用

c++ - 如何使用字符串为外部结构初始化 char 数组?

C++:是否有一个带有 'endless' 方法的 'add all' 容器?

C++:访问可能不存在的 const vector 成员 - try/catch 或 if (count != 0)?

c++ - 是否有更优雅的方式有条件地插入到 std::maps 的 std::map 中?

c++ <regex> 搜索不匹配

c++ - Qt/C++ : QTableView contextmenu and passing through information

c++ - 在设置容器的 find() 上崩溃