//通用的头文件
// 宏定义一个类实现单例需要做的一些工作。
// 每个单例类最好将其构造函数和虚析构函数设置为private
#pragma once
#define SINGLETON_DECLARE(theclass) \//头文件类中调用
public: \
static theclass * SnglPtr(); \
static void FreeSingleton(); \
private: \
static theclass * m_s##theclass; \
#define SINGLETON_IMPLEMENT(theclass) \//源文件中的预处理下面调用
theclass * theclass::m_s##theclass = NULL; \
theclass * theclass::SnglPtr() \
{ \
if (NULL == m_s##theclass) \
{ \
m_s##theclass = new(std::nothrow) theclass; \
} \
return m_s##theclass; \
} \
void theclass::FreeSingleton() \
{ \
if (NULL != m_s##theclass) \
{ \
delete m_s##theclass; \
m_s##theclass = NULL; \
} \
} \
//
宏定义C++单例模式
最新推荐文章于 2024-05-19 17:18:13 发布
本文介绍了一种使用宏定义在C++中创建单例类的方法,包括声明和实现步骤。通过宏定义,可以确保单例的唯一实例,并提供获取实例及释放单例的静态方法。构造函数和析构函数被设为私有,以防止外部直接创建或删除实例。
摘要由CSDN通过智能技术生成