单例模式

//这种单例模式称为饿汉式,如果在构造函数里不引用其他单例模式则这种模式足够用
class Singleton
{
    private:
        static Singleton _instance;
        Singleton();
        ~Singleton();
    public Singleton* getInstance()
    {
        return &_instance;
    }
}
//变量初始化 由于静态变量的初始化在Main函数之前所以是线程安全的
Singleton Singleton::_instance;
Meyers Singleton
//这种单例模式用静态局部变量实现
class Singleton
{
    public:
        static Singleton& Instance()
        {
            //静态局部变量只会在函数第一次调用的时候初始化一次
            static Singleton instance;
            return instance;
        }

    private:
        Singleton();
        ~Singleton();
        Singleton(const Singleton&);
        Singleton& operator=(const Singleton&);
}

这两种模式都是线程安全的,C++中无法使用JAVA的Singleton模式是因为C++没有自动垃圾回收机制,所以JAVA版本的会有内存泄露问题。

results matching ""

    No results matching ""