强弱引用
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_析构,当所有的强引用和弱引用都析构后,引用计数器析构。
本文深入探讨了Singleton模式的宏定义,结合Boost库中的shared_ptr和make_shared来实现单例类。通过DECLARE_SINGLETON和DEFINE_SINGLETON宏,确保了全局单例类的正确创建和销毁。在使用时,可以通过ClassName::Instance()获取单例实例。由于使用了智能指针,当所有强引用消失后,单例实例才会被析构,遵循了内存管理的最佳实践。
1万+

被折叠的 条评论
为什么被折叠?



