C++ 单例模式的模板实现
单例模式是一种创建型的设计模式(creational design patterns),使用单例模式进行设计的类在程序中只拥有一个实例(single instance),这个类称为单例类,它会提供一个全局的访问入口(global access point),关于单例模式的讨论可以参考Singleton revisited;基于这两个特点,单例模式可以有以下几种实现:
Meyer's Singleton
Scott Meyers 在 Effective C++ 的 Item 4: Make sure that objects are initialized before they're used 里面提出了一种利用 C++ 的 static
关键字来实现的单例模式,这种实现非常简洁高效,它的特点是:
- 仅当程序第一次执行到
GetInstance
函数时,执行instance
对象的初始化; - 在 C++ 11 之后,被
static
修饰的变量可以保证是线程安全的;
template<typename T>
class Singleton
{
public:
static T& GetInstance()
{
static T instance;
return instance;
}
Sing