为什么我的析构函数被调用多次

Why is my destructor getting called multiple times?

本文关键字:调用 我的 析构函数 为什么      更新时间:2023-10-16

我创建了一个类,并创建了这个类的向量。我在析构函数中放入了一条cerr消息,以查看何时调用它。我想同一个析构函数会被调用不止一次。这让我很困惑。

#include <iostream>
#include <vector>
using namespace std;
class temp {
private:
int _size = 1000;
int _myBall [1000];
int _id;
public:
temp(int id) : _id(id) {}
~temp() {
cerr << "destructor called. ID: " << _id << endl;
}
};
int main() 
{
vector<temp> myvec;
int total_count = 5;
int count = total_count;
for(int count = 0;count < total_count; count++) {
cerr << "count: " << count << endl;
myvec.push_back(temp(count));
}
myvec.clear();
cerr << "Hello World" << endl;
system("pause");
return 0;
}

控制台输出:

count: 0
destructor called. ID: 0
count: 1
destructor called. ID: 0
destructor called. ID: 1
count: 2
destructor called. ID: 0
destructor called. ID: 1
destructor called. ID: 2
count: 3
destructor called. ID: 0
destructor called. ID: 1
destructor called. ID: 2
destructor called. ID: 3
count: 4
destructor called. ID: 0
destructor called. ID: 1
destructor called. ID: 2
destructor called. ID: 3
destructor called. ID: 4
destructor called. ID: 0
destructor called. ID: 1
destructor called. ID: 2
destructor called. ID: 3
destructor called. ID: 4

由于每次std::vector调整大小时都会进行复制,因此会调用析构函数。

std::vector在构建后重新分配预先确定的内存量(足以容纳一定数量的temp实例),即capacity。每次调用push_back时,它都会评估是否仍有足够的内存来容纳新实例。一旦填满,它实际上会重新分配另一块内存(足以分配更多的temp实例),然后复制(或移动,如果可能的话)所有现有实例。这些是您看到的已记录的析构函数调用。

如果你事先知道向量需要保存多少个实例,你可以将其reserve到这个数量。

让我们看看

myvec.push_back(temp(count));

在这里,您使用temp(count)创建一个临时temp对象。然后将其存储为向量内的副本。然后临时对象被销毁。

临时对象的销毁是调用析构函数的一种情况。

然后,当向量动态调整自身大小时,它将内容复制到新的更大的数据内存中。然后,来自较小数据内存的对象将被销毁。这当然会导致析构函数被调用。这种调整大小和复制可能会发生多次。

至于向量的大小调整算法是如何工作的,这是非常具体的实现,但一种常见的方法是在大小较小时为每个push_back调整大小,然后随着大小的增加保留越来越大的块。

如果您不想进行这种调整大小和复制,那么只要您知道要存储在向量中的元素数量,您就可以从一开始设置特定的大小,并使用正常的数组索引语法来分配给元素,也可以在前面使用reserve空间。