C++ Singleton + MultiThread

2015-07-20 17:26:20 · 作者: · 浏览: 4
#include 
  
   
#include 
   
     using namespace std; template 
    
      class Singleton { public: static T *instance() { if (object == NULL) { mtx.lock(); if (object == NULL) object = new T; mtx.unlock(); } return object; } private: Singleton() {} // be here? necessary? static T *object; static mutex mtx; }; template 
     
T* Singleton ::object = NULL; template mutex Singleton ::mtx; class Foo { }; int main() { Foo *singletonFoo = Singleton ::instance(); return 0; }