原文链接:28.C++- 单例类模板(详解) - 诺谦 - 博客园
饿汉式单例模式:
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <iostream>
template <typename T>
class Singleton {
public:
static T& GetInstance()
{
static T instance;
return instance;
}
private:
Singleton();
virtual ~Singleton() {};
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
};
class Test {
friend class Singleton<Test>;
private:
Test() {
std::cout << "test create" << std::endl;
}
virtual ~Test() {};
Test(const Test&);
Test& operator=(const Test&);
};
#endif // __SINGLETON_H__
懒汉式双重加锁单例
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <iostream>
#include <mutex>
std::mutex someMutex;
template <typename T>
class Singleton {
public:
static T& GetInstance()
{
std::lock_guard<std::mutex> lck1(someMutex);
if (instance == nullptr) {
std::lock_guard<std::mutex> lck2(someMutex);
if (instance == nullptr) {
instance = new T();
}
}
return instance;
}
private:
Singleton();
virtual ~Singleton() {};
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
static T* instance;
};
template <typename T>
T* Singleton::instance = nullptr;
class Test {
friend class Singleton<Test>;
private:
Test() {
std::cout << "test create" << std::endl;
}
virtual ~Test() {};
Test(const Test&);
Test& operator=(const Test&);
};
#endif // __SINGLETON_H__
待测试