#include
#include
class Singleton
{
public:
static Singleton *GetInstance()
{
if (m_Instance == NULL )
{
//Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
EnterCriticalSection(&g_cs); //为什么Access Violation
if (m_Instance == NULL )
{
m_Instance = new Singleton ();
}
LeaveCriticalSection(&g_cs);
//UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
}
return m_Instance;
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
DeleteCriticalSection(&g_cs);
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 0;InitializeCriticalSection(&g_cs); }
static Singleton *m_Instance;
static CRITICAL_SECTION g_cs;
int m_Test;
};
Singleton* Singleton :: m_Instance = NULL;
CRITICAL_SECTION Singleton:: g_cs;
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<GetTest()<<endl;
Singleton ::DestoryInstance();
return 0;
}