单例模式,简单来说就是整个程序中只允许这一个类存在一个实例化对象。
方法来自大佬博文【戳这里】。文章分析了各类单例模式的实现,包括饿汉模式,懒汉模式的几个版本。如果赶时间,想快速上手,看这里就够了。
Talk is cheap. Show the code.
【最优实现代码】
class Singleton {
public:
static Singleton& Instance() {
static Singleton theSingleton;
return theSingleton;
}
/* more (non-static) functions here */
private:
Singleton(); // ctor hidden
Singleton(Singleton const&); // copy ctor hidden
Singleton& operator=(Singleton const&); // assign op. hidden
~Singleton(); // dtor hidden
};
将上述代码复制,将类名Singleton全部替换为你的类名既可。
实际调用就是 Singleton::instance() 得到单例对象。调用函数过程就是Singleton::instance().Function()。