智能指针的简单应用
class net_session:public boost::enable_shared_from_this<net_session>
{
public:
net_session()
{
std::cout<<"net_session.\n";
}
~net_session()
{
std::cout<<"~net_session.\n";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<boost::shared_ptr<net_session> > v_vec;
boost::weak_ptr<net_session> weak_session_ptr; //弱引用,不增加引用计数
if (true) //作用域
{
boost::shared_ptr<net_session> new_session(new net_session);
std::cout<<"引用计数:"<<new_session.use_count()<<std::endl;
v_vec.push_back(new_session);
weak_session_ptr = new_session;
std::cout<<"引用计数:"<<new_session.use_count()<<std::endl;
}
std::cout<<"引用计数:"<<v_vec[0].use_count()<<std::endl;
v_vec.clear(); //执行完后,new_session引用计数减一,对象被析构
if (weak_session_ptr.expired())
std::cout<<"对象已经被析构.\n";
getchar();
return 0;
}