写了一个小程序,来检查一下List中如何管理存储的对象。
#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;
class MyClass
{
public:
int nMember;
int * pMember;
public:
MyClass(void)
{
cout<<"New my Class"<<endl;
nMember = 0;
pMember = &nMember;
cout<<" pMember is "<<pMember<<endl;
};
~MyClass(void)
{
cout<<"Free my Class"<<endl;
cout<<" The number is "<<nMember<<endl;
cout<<" pMember is "<<pMember<<endl;
cout<<" *pMember is "<<*pMember<<endl;
*pMember = 15;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
list<MyClass> m_Container;
MyClass *a = new MyClass();
a->nMember = 1;
m_Container.push_back(*a);
a->nMember = 2;
delete a;
return 0;
}
程序的运行结果如下:
显然当调用push_back时,生成了一个新的实例,所以出现了两个析构函数的调用。同时观察一下pMember值的变化,这可是很容易出问题的地方!
如果List存储的是对象指针可就要小心了。