简体   繁体   English

将静态变量初始化为类成员或局部函数变量(Singleton示例)

[英]Static variable initialization as a class member or local function variable (Singleton example)

I will demonstrate my question using a Singleton pattern but it is a broader question. 我将使用Singleton模式演示我的问题,但这是一个更广泛的问题。 Please spare me the "Singletons are evil" lectures. 请饶恕我说“ Singletons是邪恶的”演讲。

Version 1 of Singleton Singleton版本1

class Singleton
{
  public:
    static Singleton& getInstance()
    {
      static Singleton instance; // This becomes a class member in Ver.2
      return instance;
    }

  private:
    // Constructor, forbid copy and assign operations etc...
}

Version 2 of Singleton Singleton版本2

class Singleton
{
  public:
    static Singleton& getInstance()
    {
      return instance;
    }

  private:
    static Singleton instance; // I'm here now!

    // Constructor, forbid copy and assign operations etc...
}

I will now explain what I think will be the difference is between the two: 现在,我将解释两者之间的区别:

Version 1 instance will only be initialized once the flow of the program reaches the actual definition of instance (ie some part of the program requests an instance using Singleton::getInstace() ). 仅当程序流达到instance的实际定义时(即,程序的某些部分使用Singleton::getInstace()请求instance才会初始化版本1 instance Lazy instantiated in other words. 换句话说,懒惰实例化。 It will only be destroyed when the program terminates. 在程序终止时销毁它。

Version 2 instance will be initialized at the start of the program, before main() is called. 在调用main()之前,版本2 instance将在程序开始时进行初始化。 Will also be destroyed only when the program terminates. 仅在程序终止时也将被销毁。

First of all, am I correct in the above assumptions? 首先,我对上述假设是否正确?
Second, Is this behavior of initialization universal (say for global variables and functions)? 其次,这种初始化行为是否通用(例如针对全局变量和函数)?
Last, Are there any other nuances I should be alerted about concerning this? 最后,关于此事,是否应该提醒我其他细微之处?

Thanks! 谢谢!

You are correct. 你是对的。

You should also notice that the 2nd version does not guarantee when will the object be created, only that it will be before the main function is called. 您还应该注意,第二版本不保证将在何时创建对象,仅保证在主函数被调用之前。

This will cause problems if that singleton depends on other singletons and etc 如果该单例依赖于其他单例,则将导致问题。

That is, the first version will give you greater control over your code, initialization order and of course - less bugs :) 也就是说,第一个版本将使您可以更好地控制代码,初始化顺序,当然也可以减少错误:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM