C++ Singleton + MultiThread

#include <iostream>
#include <mutex>
using namespace std;

template <class T>
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 <class T> T* Singleton<T>::object = NULL; template <class T> mutex Singleton<T>::mtx; class Foo { }; int main() { Foo *singletonFoo = Singleton<Foo>::instance(); return 0; }


posted @ 2018-03-23 12:47  llguanli  阅读(116)  评论(0编辑  收藏  举报