写这个单例模式的要点:
头文件:<stdlib.h> <iostream>
① 两个静态成员变量:Singeleton* pInstance、pthread_once_t once
② 初始化 pInstance = nullptr;once = PTHREAD_ONCE_INIT
③ 在静态成员函数中注册pthread_once(&once,init_r)
④ 在init_r中注册销毁单例对象的函数,atexit(destory),并将pInstance = new Singeleton()
⑤ 将构造函数和析构函数私有化;将拷贝构造和赋值运算符函数delete
#include <iostream>
#include <stdlib.h>
using namespace std;
class Singeleton
{
public:
static Singeleton* getInstance()
{
pthread_once(&once,init_r);
return pInstance;
}
void init(int ix,int iy)
{
this->ix = ix;
this->iy = iy;
}
void myPrint()
{
cout << "ix:" << ix << ",iy:" << iy << "\n";
}
private:
static void init_r()
{
atexit(destory);
pInstance = new Singeleton();
}
static void destory()
{
delete pInstance;
}
~Singeleton() = default;
Singeleton() = default;
Singeleton& operator=(const Singeleton&) = delete;
Singeleton(const Singeleton&) = delete;
private:
int ix;
int iy;
static Singeleton* pInstance;
static pthread_once_t once;
};
Singeleton* Singeleton::pInstance = nullptr;
pthread_once_t Singeleton::once = PTHREAD_ONCE_INIT;
int main(int argc, char const *argv[])
{
Singeleton* p1 = Singeleton::getInstance();
Singeleton* p2 = Singeleton::getInstance();
cout << p1 << "\n";
cout << p2 << "\n";
p1->init(2,5);
p1->myPrint();
return 0;
}
注:pthread_once在程序中只会执行一次,并且在执行的时候会调用静态的init_r,这个函数对单例对象进行了初始化,并且注册了atexit的destory函数,保证了单例对象的资源被释放