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

C++ 静态变量初始化为类成员或局部函数变量(单例示例),c++,static,initialization,singleton,C++,Static,Initialization,Singleton,我将使用单例模式演示我的问题,但这是一个更广泛的问题。请不要再给我讲“单身是邪恶的”了 版本1的Singleton class Singleton { public: static Singleton& getInstance() { static Singleton instance; // This becomes a class member in Ver.2 return instance; } private:

我将使用单例模式演示我的问题,但这是一个更广泛的问题。请不要再给我讲“单身是邪恶的”了

版本1的
Singleton

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...
}
class Singleton
{
  public:
    static Singleton& getInstance()
    {
      return instance;
    }

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

    // Constructor, forbid copy and assign operations etc...
}
第2版的
Singleton

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...
}
class Singleton
{
  public:
    static Singleton& getInstance()
    {
      return instance;
    }

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

    // Constructor, forbid copy and assign operations etc...
}
我现在将解释我认为两者之间的区别:

版本1
实例
仅在程序流达到
实例
的实际定义时才会初始化(即程序的某些部分使用
Singleton::getInstance()
)请求实例)。换句话说,懒惰被实例化了。 只有当程序终止时,它才会被销毁

在调用
main()
之前,将在程序开始时初始化版本2
instance
。也将仅在程序终止时销毁

首先,我的上述假设正确吗?
第二,这种初始化行为是通用的(比如全局变量和函数)?
最后,关于这一点,是否还有其他细微差别需要提醒我

谢谢

你说得对

您还应该注意,第二个版本并不保证何时创建对象,只保证在调用main函数之前创建对象

如果该单例依赖于其他单例等,这将导致问题

也就是说,第一个版本将使您能够更好地控制代码、初始化顺序,当然还有更少的bug:)