#include <iostream>
using namespace std;
class Single{
private: // 单例模式
static Single* single; // pointer
Single(): data(10){ // default constructor is necessary
}
~Single(){
cout << "deconstruct single" << endl;
}
class GC{ // this nested class is static
public:
~GC(){ // must be public
if(single != NULL){
delete single;
single = NULL;
cout << "deconstruct GC" << endl;
}
}
};
static GC gc; // just for deleting the single
int data;
public:
static Single* getInstance(){ // pointer
return single;
}
void print(){ // member function
cout << data << endl;
}
};
Single* Single::single = new Single; // this step keeps thread safe, only once
Single::GC Single::gc; // this step is necessary to trigger the gc deconstructor, pay attention to the modifier
int main(){
Single * single = Single::getInstance();
single->print();
return 0;
}
线程安全的单例模式
最新推荐文章于 2024-09-09 22:12:12 发布