C++ singleton vs. global static object

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.

Leave a Comment