强弱引用
singleton模式的宏定义
factory模式
单例类的使用
#include "boost/shared_ptr.hpp"
#include "boost/make_shared.hpp"
#define DECLARE_SINGLETON(ClassName); \
public: \
static boost::shared_ptr<ClassName>& Instance(void); \
private: \
static boost::shared_ptr<ClassName> instance_; \
public: \
#define DEFINE_SINGLETON(ClassName) \
boost::shared_ptr<ClassName> ClassName::instance_; \
boost::shared_ptr<ClassName>& ClassName::Instance(void) \
{ \
if(!instance_){ \
instance_ = boost::make_shared<ClassName>(); \
} \
return instance_; \
} \
使用时利用ClassName:Instance()可以获取全局单例类,因为是make_shared 创建出来的,所以,在脱离作用域后,引用不在,当所有的强引用析构后
创建出来的单例instance_析构,当所有的强引用和弱引用都析构后,引用计数器析构。
singleton模式的宏定义
factory模式
单例类的使用
#include "boost/shared_ptr.hpp"
#include "boost/make_shared.hpp"
#define DECLARE_SINGLETON(ClassName); \
public: \
static boost::shared_ptr<ClassName>& Instance(void); \
private: \
static boost::shared_ptr<ClassName> instance_; \
public: \
#define DEFINE_SINGLETON(ClassName) \
boost::shared_ptr<ClassName> ClassName::instance_; \
boost::shared_ptr<ClassName>& ClassName::Instance(void) \
{ \
if(!instance_){ \
instance_ = boost::make_shared<ClassName>(); \
} \
return instance_; \
} \
使用时利用ClassName:Instance()可以获取全局单例类,因为是make_shared 创建出来的,所以,在脱离作用域后,引用不在,当所有的强引用析构后
创建出来的单例instance_析构,当所有的强引用和弱引用都析构后,引用计数器析构。