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; }


【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/llguanli/p/8629707.html