多个模板类破坏?

时间:2014-03-21 11:56:21

标签: c++ vector destructor

这是一个简单的测试:

#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是一个负责任的析构函数的真正类时,它看起来并不那么有趣。 有什么建议? 提前谢谢。

2 个答案:

答案 0 :(得分:5)

您将获得多个类析构函数日志,因为在向量中添加对象时存在对象复制。同时记录复制构造函数,你会看到它是平衡的。如评论中所示,如果您使用的是C ++ 11,请同时登录移动构造函数。

这就是为什么如果对象构造是扩展的,你可以在向量中使用指针(smart_ptr)。或者保留足够的空间并使用emplace_back(如果使用C ++ 11,则再次使用)。

答案 1 :(得分:1)

构造函数C:1

调用

创建临时对象C(1)作为vec.push_back(i + 1)的参数;  当i = 0时

析构函数C:1

将此临时对象复制到向量的对象中,之后将其删除。

构造函数C:2

调用

创建临时对象C(2)作为vec.push_back(i + 1)的参数;  当i = 1时

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

如果您要致电会员功能储备

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

然后就没有重新分配,你也看不到下一个输出。

析构函数C:1

删除旧区域内存中向量的第一个元素

析构函数C:2

临时对象被复制到向量的对象中,之后被删除。

相关问题