64,684
社区成员
发帖
与我相关
我的任务
分享
#include <assert.h>
template <typename T>
class Singleton
{
//private:
/** \brief Explicit private copy constructor. This is a forbidden operation.*/
Singleton(const Singleton<T> &);
/** \brief Private operator= . This is a forbidden operation. */
Singleton& operator=(const Singleton<T> &);
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
ms_Singleton = static_cast< T* >( this );
}
~Singleton( void )
{ assert( ms_Singleton ); ms_Singleton = 0; }
static T& getSingleton( void )
{ assert( ms_Singleton ); return ( *ms_Singleton ); }
static T* getSingletonPtr( void )
{ return ms_Singleton; }
};
class A:public Singleton<A>
{
};
int main()
{
A* a1=new A();
A* a2=new A();
return 1;
}
#include <cassert>
template<typename T>
class Singleton {
//private:
/** \brief Explicit private copy constructor. This is a forbidden operation.*/
Singleton(const Singleton<T> &);
/** \brief Private operator= . This is a forbidden operation. */
Singleton& operator=(const Singleton<T> &);
protected:
static T* ms_Singleton;
public:
Singleton(void) {
assert( !ms_Singleton);
ms_Singleton = static_cast<T*>(this);
}
~Singleton(void) {
assert( ms_Singleton);
ms_Singleton = 0;
}
static T& getSingleton(void) {
assert( ms_Singleton);
return (*ms_Singleton);
}
static T* getSingletonPtr(void) {
return ms_Singleton;
}
};
template<typename T>
T* Singleton::ms_Singleton = NULL;
class A: public Singleton<A> {
};
int main() {
A* a1 = new A();
A* a2 = new A();
return 1;
}