C++ singleton vs. global static object

前端 未结 8 1421
孤街浪徒
孤街浪徒 2020-11-28 20:06

A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. s

8条回答
  •  旧巷少年郎
    2020-11-28 20:46

    Reason 1:
    Singletons are easy to make so they are lazy build.
    While you can do this with globals it take extra work by the developer. So by default globals are always initialized (apart from some special rules with namespaces).

    So if your object is large and/or expensive to build you may not want to build it unless you really have to use it.

    Reason 2:
    Order of initialization (and destruction) problem.

    GlobalRes& getGlobalRes()
    {
        static GlobalRes instance;  // Lazily initialized.
        return instance;
    }
    
    
    GlobalResTwo& getGlobalResTwo()
    {
        static GlobalResTwo instance;  // Lazy again.
        return instance;
    }
    
    
    // Order of destruction problem.
    // The destructor of this object uses another global object so
    // the order of destruction is important.
    class GlobalResTwo
    {
        public:
            GlobalResTwo()
            {
                getGlobalRes();
                // At this point globalRes is fully initialized.
                // Because it is fully initialized before this object it will be destroyed
                // after this object is destroyed (Guaranteed)
            }
            ~GlobalResTwo()
            {
                // It is safe to use globalRes because we know it will not be destroyed
                // before this object.
                getGlobalRes().doStuff();
            }
    };
    

提交回复
热议问题