单列宏第二版Demo
#include <iostream.h>
/*
*
* Copyright (c) 2006
* Author: RobertBaker
* DECLARE_SINGLETON Ver 2.0
*/
#define DECLARE_SINGLETON(CLASSNAME) \
public: \
static CLASSNAME * const & GetSingleton(bool bCreate = true) { \
static CLASSNAME *s_pSingleton = 0; \
static Close##CLASSNAME close##CLASSNAME; \
\
if (s_pSingleton == 0 && bCreate) { \
s_pSingleton = new CLASSNAME; \
} \
\
return s_pSingleton; \
} \
\
static bool IsCreatedSingleton() { return GetSingleton(false) != 0; } \
static void CloseSingleton() { \
CLASSNAME *&p##CLASSNAME = const_cast<CLASSNAME *&>(GetSingleton()); \
\
if (p##CLASSNAME != 0) { \
delete p##CLASSNAME; \
p##CLASSNAME = 0; \
} \
} \
private: \
struct Close##CLASSNAME { \
Close##CLASSNAME() {} \
~Close##CLASSNAME() { CloseSingleton(); } \
}; \
class A
{
DECLARE_SINGLETON(A)
protected:
A() {}
~A() {}
};
int main()
{
cout << A::IsCreatedSingleton() << endl;
A *pA = A::GetSingleton();
cout << A::IsCreatedSingleton() << endl;
return 0;
}