1.C++的Vector 保存原始指针 的时候 Vector 析构的时候是不会释放指针指向的堆对象,
2.如果用Vector保存智能指针是可以释放智能指针 所指向的对象的
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Human
{public:
Human(){ cout << "con Human" << endl; }
~Human(){ cout << "des Human" << endl; }};
class HuamanList
{public:
HuamanList(){ cout << "con HuamanList" << endl; }
~HuamanList(){ cout << "des HuamanList" << endl; }
void addHuman(shared_ptr<Human> human){ m_humanList.push_back(human); }
private:vector<shared_ptr<Human>> m_humanList;
};
int _tmain(int argc, _TCHAR* argv[])
{ HuamanList * list = new HuamanList();
{ shared_ptr<Human> newHuman;
newHuman.reset(new Human());//newHuman的引用计数为2
list->addHuman(newHuman);
}//newHuman的引用计数为1,所以{}括号不要省略掉
cout << "addHuman" << endl;
delete list;
cout << "clear HumanList" << endl;
system("pause");
return 0;
}
这是测试代码.