class singleClass { public: static singleClass* getInstance() { //双判断保证在多线程下不会每次getInstance都加锁 if(!m_instance) { std::unique_lock<std::mutex> myMutex(resoure_mutex); if(!m_stance) { m_instance = new singleClass(); //定义一个静态变量,以达到析构singleClass单例的作用 static GcSingle gc; } return m_instance; } }
//类中类,辅助删除单例用
class Gcsingle{
public:
~Gcsingle(){
if(singleClass::m_instance){
delete singleClass::m_instance;
singleClass::m_instance=NULL;
}
}
}; private: //私有构造 singleClass(){} static singleClass* m_instance; };
singleClass* singleClass::m_instance=NULL;
使用:
singleClass* p_single = singleClass::getInstance();