【发布时间】:2016-04-08 18:01:10
【问题描述】:
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
class A
{
static int k;
public:
A(){k++ ; cout << "constructor : " <<k<< endl;};
~A(){k--; cout << "destructor : " << k <<endl;};
void show() { cout<<"current value of k = "<<k<<endl; }
};
int A::k = 0;
int main( )
{
vector<A> test;
test.push_back(A());
test.emplace(test.end(), A());
test[0].show();
cout<<test.size()<<endl;
return 0;
}
输出:
构造函数:1
析构函数:0
构造函数:1
析构函数:0
析构函数:-1
k 的当前值 = -1
2
析构函数:-2
析构函数:-3
为什么析构函数被调用了太多次,因为构造函数只被调用了两次,所以它应该只被调用两次?如何避免这种情况?
【问题讨论】:
-
当您调用
emplace时,您应该将参数提供给类构造函数,而不是类的实例。 -
@Sean 没有错。该实例将传递给复制构造函数。与替代方案相比,它可能效率稍低,但不是错误。
标签: c++ destructor