#include<iostream> #include<mutex> using namespace std; mutex mtx; class CSingleton { private: CSingleton() //构造函数是私有的 { } static CSingleton *Instance; public: static CSingleton * GetInstance() { if(Instance == NULL){ mtx.lock(); if(Instance == NULL) Instance = new CSingleton(); cout<<"This is singleton"<<endl; mtx.unlock(); } return Instance; } void print() { cout<<"aaa"<<endl; } }; CSingleton* CSingleton::Instance = 0;//类静态变量需要在类外初始化 int main() { CSingleton* a = CSingleton::GetInstance(); a->print(); return 0; }
原文:https://www.cnblogs.com/jodio/p/11546052.html