单形模式的延迟初始化 [英] Lazy initialization with singleton pattern

查看:95
本文介绍了单形模式的延迟初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否会促进延迟初始化

或者一旦某人包含了 singletonInstance (或甚至在程序启动时)?

Would the following code facilitate lazy initialization?
Or would the singletonInstance be created as soon as somebody includes the header (or even at program startup time)?

class SingletonClass
{
    private:
         SingletonClass();
        ~SingletonClass();

    public: 

        static const SingletonClass& Instance()
        {
            static SingletonClass singletonInstance;
            return singletonInstance; 
        }
};


推荐答案

这称为 Meyers singleton ,它们是惰性实例化。

This is known as the Meyers singleton and they are lazy instantiated.

有一些注意事项:


  • 单身人士会在结束程序的顺序与它们的创建顺序相反,因此可能存在依赖性问题。

  • C ++ 03不保证在多线程环境中不会出现竞争条件。

这篇关于单形模式的延迟初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆