所有單例模類直接繼承此模板即可,線程安全,效率高(無鎖),延時構造。
#include <iostream>
using namespace std;
template <typename T>
class Singleton {
public:
//外部獲取單例的接口
static T& getInstance() {
static Token token;
static T instance(token); //函數靜態變量可以實現延時構造。
return instance;
}
//禁止拷貝
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
protected:
//只有子類才能獲取令牌。
struct Token{};
//構造和析構函數私有化
Singleton() = default;
virtual ~Singleton() = default;
};
//具體單例模式
class Single : public Singleton<Single> {
public:
//Token保證,父類需要調用,其他人無法調用。
Single(Token token) {
cout << "construct: " << this << endl;
//做你想做的事情。
}
~Single() = default;
//禁止拷貝
Single(const Single&) = delete;
Single& operator=(const Single&) = delete;
};
int main()
{
cout << "main begin" << endl;
Single &s1 = Single::getInstance();
Single &s2 = Single::getInstance();
cout << boolalpha << (&s1 == &s2) << endl;
cout << "main end" << endl;
return 0;
}