多个模板类破坏?

-2 c++ destructor vector

这是一个简单的测试:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

constructor C: 1
destructor C: 1
constructor C: 2
destructor C: 1
destructor C: 2
Go out --->
destructor C: 1
destructor C: 2
Run Code Online (Sandbox Code Playgroud)

当C是一个负责任的析构函数的真正类时,它看起来不那么有趣.有什么建议?先感谢您.

Eri*_*tin 5

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

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