#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
std::mutex mtx;
std::once_flag g_flag;//系统定义的标记
class testdanli
{
public:
static void CreateInstance()//只被调用1次
{
myPtr = new testdanli();
static deletetest c1;
cout << "被执行" << endl;
}
static testdanli* instance()
{
std::call_once(g_flag, CreateInstance);
//if (myPtr == nullptr)
//{
// std::lock_guard<std::mutex> m(mtx);
// if (myPtr == nullptr)
// {
// myPtr = new testdanli();
// static deletetest c1;
// }
//}
return myPtr;
}
//~testdanli()
//{
// if (myPtr != nullptr)
// {
// delete myPtr;
// myPtr = nullptr;
// }
//}
class deletetest
{
public:
~deletetest()
{
if (testdanli::myPtr != nullptr)
{
delete testdanli::myPtr;
testdanli::myPtr = nullptr;
}
}
};
private:
testdanli() {};
static testdanli* myPtr;
};
testdanli* testdanli::myPtr = nullptr;
void treadEnter()
{
testdanli* test = testdanli::instance();
}
int main()
{
thread th1(treadEnter);
thread th2(treadEnter);
th1.join();
th2.join();
return 0;
}
当程序推出的testdanli类中的析构函数不会被调用,而deletetest类的析构函数会被调用。具体原因,暂未清楚,断点调试的结果。