简体   繁体   中英

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. Please spare me the "Singletons are evil" lectures.

Version 1 of 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...
}

Version 2 of Singleton

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() ). 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. 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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