多个模板类销毁

Multiple template class destruction?

本文关键字:      更新时间:2023-10-16

这是一个简单的测试:

#include <iostream>
#include <vector>
using namespace std;
class C
{
public:
    int _a;
    C(int a) { cout << "constructor C: " << (_a = a) << endl; }
    ~C()     { cout << "destructor C: "<< _a << endl; }
};
int main()
{
    vector<C> vec;
    for(int i=0; i<2; i++)
        vec.push_back(i+1);
    cout << "Go out --->n";
    return 0;
}
输出:

constructor C: 1
destructor C: 1
constructor C: 2
destructor C: 1
destructor C: 2
Go out --->
destructor C: 1
destructor C: 2

当C是一个真正具有负责析构函数的类时,它看起来就不那么有趣了。有什么建议吗?

您将获得多个类析构函数日志,因为在vector中添加对象时存在对象复制。同时登录复制构造器,你会看到它平衡了。如注释所示,如果您使用的是c++ 11,也要登录move构造函数。

这就是为什么如果对象构造是扩展的,那么在vector中使用指针(smart_ptr)。或者预留足够的空间并使用emplace_back(如果使用c++ 11的话)。

构造器C: 1

创建临时对象C(1)作为vec.push_back(i+1)的实参时调用

;当I =0

C: 1

这个临时对象被复制到vector对象中,然后被删除。

构造函数C: 2

创建临时对象C(2)作为vec.push_back(i+1)的实参时调用

;当I =1

vector需要分配一个新的内存区域来容纳第二个元素。因此,它重新分配内存并复制新内存中的第一个元素。

如果要调用成员函数reserve

vector<C> vec;
vec.reserve( 2 );

则不会进行重新分配,并且您不会看到下一个输出。

C: 1

旧区域内存中vector的第一个元素被删除

C: 2

将临时对象复制到vector对象中,然后将其删除。

相关文章:
  • 没有找到相关文章