为什么我的析构函数被调用多次
Why is my destructor getting called multiple times?
我创建了一个类,并创建了这个类的向量。我在析构函数中放入了一条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
空间。
相关文章:
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 什么时候可以使用常量装饰调用我的重载函数?
- 为什么当我做复制和交换习语时不调用我的复制构造函数?
- 钩/绕道 d3d9 (现在/结束场景) - 似乎调用我的函数然后崩溃
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在linux中,mono调用我的.so-lib返回System.EntryPointNotFoundException
- 当我从头文件和实现文件调用我的函数到我的主文件时,我没有得到任何输出
- 为什么没有调用我的回调?
- 如何制作指针来调用我的成员函数
- 如何在Android Studio中编写CMakelists来调用我的C 项目(JNI)的功能
- 为什么在这种情况下不调用我的移动构造函数?(首先分配 r 值引用并创建对象)
- 我如何调用我的3个数据成员中每个人的设置方法,然后显示由我的设置方法设置的值
- 为什么没有调用我的覆盖方法
- 我的类中有方法的指针数组,但我不能调用我的方法.代码如下
- C++模板:无法从 main.cpp 调用我的函数
- 为什么我继承的构造函数调用我的基本默认构造函数
- 我如何在C#GUI中调用我的C 程序
- SetWindowsHookEx没有调用我的回调
- c++ Glut 显示需要调用我的绘制函数,但我无法传递任何参数
- 如何从对象中调用我的set回调函数