自从阿里被虐了回来就想写一篇单例模式了,一直拖到现在,从前也查了好多,自我感觉还是一个不错的,背了下来,今天再查资料发现还是漏洞太多了,真的不的不佩服C++是多么的强大啊!~
首先拿我之前的那个来分享:
class CSingleton
{
public:
static CSingleton * GetInstance()
{
if (NULL == m_pInstance)
m_pInstance = new CSingleton();
return m_pInstance;
}
static void Release() //必须,否则会导致内存泄露
{
if (NULL != m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
}
protected:
CSingleton()
{
cout << "CSingleton" << endl;
};
static CSingleton * m_pInstance;
};
CSingleton* CSingleton::m_pInstance = NULL;
这个当时我认为还可以,但是拿去阿里面试官那说这个还是有点小问题,然后就说不适合多线程。
今天回来查资料大多都不适合多线程,还有自己又发现了一些错误,可以进行深拷贝和友元可以访问。所以修改如下:
class CSingleton
{
public:
static CSingleton * GetInstance()
{
if (NULL == m_pInstance)
{
Lock lock(cs);
m_pInstance = new CSingleton();
}
return m_pInstance;
}
static void Release() //必须,否则会导致内存泄露
{
if (NULL != m_pInstance)
{
Lock lock(cs);
delete m_pInstance;
m_pInstance = NULL;
}
}
protected:
CSingleton()
{
cout << "CSingleton" << endl;
};
static CSingleton * m_pInstance;
private:
CSingleton();
CSingleton(const CSingleton &);
CSingleton& operator = (const CSingleton &);
};
CSingleton* CSingleton::m_pInstance = NULL;
至于如何加锁,VC里边MFC有临界区,其他的也都有,各不相同就不写了!~