enable_shared_from_this

编写用来学习boost的enable_shared_from_this的测试代码,仅用来学习。

// shared_ptr.cpp : 定义控制台应用程序的入口点。
//made by davidsu33
//2014-5-12

#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/checked_delete.hpp>
#include <iostream>

using namespace std;

class Base;

class Base : public boost::enable_shared_from_this<Base>
{
public:
	Base()
	{
		cout<<"ctor Base"<<endl;
	}

	~Base()
	{
		cout<<"dtor Base"<<endl;
	}
};

struct Deleter
{
	void operator()(Base* p)
	{
		boost::checked_delete(p);
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	boost::shared_ptr<Base> b (new Base, Deleter());
	cout<<"use_count="<<b.use_count()<<endl;

	boost::shared_ptr<Base> pb = b->shared_from_this();
	cout<<"pb use_count="<<pb.use_count()<<endl;
	cout<<"b   use_count="<<b.use_count()<<endl;

	//错误用法
	//Base b;

	getchar();
	return 0;
}


你可能感兴趣的:(C++,boost)