#include <iostream>
#include <map>
#include <memory>
using namespace std;
class Test
{
public:
Test(int i)
{
m_count = i;
cout << "Test()" << endl;
}
~Test()
{
cout << "~Test()" << endl;
}
int m_count;
};
shared_ptr<Test> creatTest(int i)
{
shared_ptr<Test> pTest =make_shared<Test>(i);
cout<<"CreateTest:: ref1 "<<pTest.use_count()<<endl;
return pTest;
}
void main()
{
shared_ptr<Test> pTest;
map<int,shared_ptr<Test>> obj_map; //局部变量,自动释放
cout<<"size of plist "<<sizeof(obj_map)<<" shared_ptr Test: "<< sizeof(pTest)<<endl;
//1.map赋值
for(int i=0;i<10;i++)
{
//obj_map[i]=make_shared<Test>(i);//创建对象赋值增加引用计数
pTest = creatTest(i);
cout<<"LOOP(0~9) ref1::"<<pTest.use_count()<<endl;
obj_map[i]=pTest;//创建对象赋值增加引用计数
cout<<"LOOP(0~9) ref2::"<<pTest.use_count()<<endl;
}
// 2.查询&删除
for(auto itMap = obj_map.begin();itMap!=obj_map.end();)
{
if((itMap)->first == 5)
{
itMap = obj_map.erase(itMap); //会释放pTest对象,新标准智能指针会自动析构
}
else
{
cout<<"Loop Map:"<<(itMap)->second->m_count<<endl;
itMap++;
}
}
// 3. 查询
auto itMap = obj_map.find(6);
if(itMap != obj_map.end())
{
cout<<"Map find key: "<<(*itMap).second->m_count<<endl;
itMap = obj_map.erase(itMap);
}
//cout<<"shared_ptr plist ref::"<<.use_count()<<endl;
cout<<"shared_ptr pTest ref::"<<pTest.use_count()<<endl;
}