本文介绍了一种使用嵌套类释放单例对象的方法。
#include<iostream>
#include<thread>
#include<mutex>
#include<algorithm>
using namespace std;
mutex resource_mutex;
class MyCAS
{
public:
static MyCAS *GetInstance()
{
//双重锁定
if (m_instance == NULL)
{
unique_lock<mutex> guard(resource_mutex);
if (m_instance == NULL)
{
m_instance = new MyCAS();
static CASDestructor destructor; //声明静态变量
}
}
return m_instance;
}
//嵌套类,用来释放对象
class CASDestructor
{
public:
~CASDestructor()
{
if (m_instance)
{
delete m_instance; //释放对象
m_instance = NULL;
}
}
};
private:
MyCAS() {}
static MyCAS *m_instance;
};
MyCAS *MyCAS::m_instance = NULL;
void MyFunc()
{
cout << "线程开始" << endl;
MyCAS *ptr = MyCAS::GetInstance();
cout << "线程结束" << endl;
}
int main()
{
thread obj1(MyFunc);
thread obj2(MyFunc);
obj1.join();
obj2.join();
return 0;
}