这次使用一个pthread_once函数来实现,关于pthread_once函数的介绍在这里https://www.cnblogs.com/lit10050528/p/4325888.html。
#include <pthread.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
//让单例类对象自动释放
//版本三: atexit + pthread_once
class Singleton
{
public:
static Singleton * getInstance()
{
pthread_once(&_once, init);
return _pInstance;
}
static void init()
{
_pInstance = new Singleton;
atexit(destroy);
}
static void destroy()
{
cout << "destroy()" << endl;
if(_pInstance)
delete _pInstance;
}
private:
Singleton(){}
~Singleton(){}
private:
static Singleton * _pInstance;
static pthread_once_t _once;
};
Singleton * Singleton::_pInstance = NULL;
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;
int main()
{
Singleton::getInstance();
return 0;
}