map+shared_ptr


#include
#include
#include

using namespace std;

class Test
{
public:
    Test(int i)
    {
        m_count = i;
        cout << "Test()" << endl;
    }

    ~Test()
    {
        cout << "~Test()" << endl;
    }

    int m_count;
};


shared_ptr creatTest(int i)
{
    shared_ptr pTest =make_shared(i);
    cout<<"CreateTest:: ref1 "<     return pTest;
}


void main()
{

   shared_ptr pTest;
   map> obj_map;   //局部变量,自动释放
   cout<<"size of plist "<    //1.map赋值
   for(int i=0;i<10;i++)
   {
      //obj_map[i]=make_shared(i);//创建对象赋值增加引用计数
      pTest = creatTest(i);
      cout<<"LOOP(0~9) ref1::"<       obj_map[i]=pTest;//创建对象赋值增加引用计数
      cout<<"LOOP(0~9) ref2::"<    }

   // 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<            itMap++;
       }


   }
   // 3. 查询
   auto itMap = obj_map.find(6);
   if(itMap != obj_map.end())
   {
       cout<<"Map find key: "<<(*itMap).second->m_count<        itMap = obj_map.erase(itMap);
   }

 

   //cout<<"shared_ptr plist ref::"<<.use_count()<    cout<<"shared_ptr pTest ref::"< }

 

你可能感兴趣的:(c++11)