C++ singleton vs. global static object

前端 未结 8 1428
孤街浪徒
孤街浪徒 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:35

    Actually, in C++ preferred way is local static object.

    Printer & thePrinter() {
        static Printer printer;
        return printer;
    }
    

    This is technically a singleton though, this function can even be a static method of a class. So it guaranties to be constructed before used unlike with global static objects, that can be created in any order, making it possible to fail unconsistently when one global object uses another, quite a common scenario.

    What makes it better than common way of doing singletons with creating new instance by calling new is that object destructor will be called at the end of a program. It won't happen with dynamically allocated singleton.

    Another positive side is there's no way to access singleton before it gets created, even from other static methods or from subclasses. Saves you some debugging time.

提交回复
热议问题