我有这个下面的程序,我通过引用函数传递一个向量myFunc
,在这个函数里面,我向向量添加了一些元素.
我没有释放用new创建对象,现在忽略由此引起的内存泄漏.
后myFunc()
执行完成我打印变量构造函数和析构函数知道多少次的构造函数和析构函数是如何调用.
输出是:
Before Exiting 5 7
Run Code Online (Sandbox Code Playgroud)
我创建了5个对象,以便ctor
为5
.但为什么dtor
7
呢?额外的两个计数从何而来?我错过了什么吗?
#include
#include
using namespace std;
static int ctor = 0;
static int dtor = 0;
class MyClass
{
public:
MyClass(int n)
{
i = n;
ctor++;
// cout << "Myclass ctor " << ctor << endl;
}
~MyClass()
{
dtor++;
// cout << "Myclass dtor" << dtor << endl;
}
private:
int i;
};
void myFunc(vector<MyClass> &m);
void myFunc(vector<MyClass> &m)
{
MyClass *mc;
for(int i = 0; i < 5; i++)
{
mc = new MyClass(i);
m.push_back(*mc);
}
}
int main()
{
vector<MyClass> m;
vector<MyClass>::iterator it;
myFunc(m);
cout << "Before Exiting " << ctor << " " << dtor << endl;
}
Run Code Online (Sandbox Code Playgroud)
向量复制对象,但只有int
构造函数递增ctor
.这不是考虑复制构造的对象,并且因为你没有提供,所以编译器为你提供了它.
加
MyClass(const MyClass& rhs) i(rhs.i) { ++ctor; }
Run Code Online (Sandbox Code Playgroud)
到你的班级,看看是否能平衡计数.