share_ptr的正确使用方法

时间:2021-03-22 08:40:13

实在是看不惯度娘出来的share ptr的例子,没有实用性,而且还不清晰,举一个场景如下:

假设游戏玩家登陆时要登记到一个管理用的vector中,登出时删除,程序如下:

注意对象时在函数结束时才被释放的。


#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/noncopyable.hpp>

#include <iostream>
#include <vector>
#include <string>

using namespace std;
class player;

typedef boost::shared_ptr<player> pplayer;
typedef vector<pplayer> player_container;

player_container PC;

class player:public boost::enable_shared_from_this<player>,boost::noncopyable
{
public:
 player(string name_)
 {
  name = name_;
  cout << "new>>>>" << name <<":"<<__FUNCTION__ << ":" << __LINE__ << endl;
 }

 ~player()
 {
  cout << "delete>>>>" << name <<":"<< __FUNCTION__ << ":" << __LINE__ << endl;
 }

 static pplayer CreatePlayer(string name)
 {
  pplayer pp(new player(name));
  return pp;
 }

 void Login()
 {
  cout << name  <<" login:" << endl;
  PC.push_back(shared_from_this());
 }

 void Logout()
 {
  cout << name << " logout " << endl;
  pplayer me = shared_from_this();
  player_container::iterator it = std::find(PC.begin(), PC.end(), me);
  PC.erase(it);
 }

 string GetName() const
 {
  return name;
 }
private:
 string name;
 int account;
 int charid; 
};


void player_manager()
{
 pplayer pp1 = player::CreatePlayer("zhangSan");
 pp1->Login();
 pp1->Logout();

 pplayer pp1_new = pp1;
 pplayer pp1_new2 = pp1;

 cout << "pp1 share count: " << pp1->shared_from_this().use_count() << endl;
 pplayer pp2 = player::CreatePlayer("LiSi");
 pp2->Login();
 pp2->Logout();

 pplayer pp3 = player::CreatePlayer("Wang2Mazi");
 pp3->Login();
 pp3->Logout();
}

int main(int argc,char**agrv)
{
    player_manager();
 system("pause");
 return 0;
}