Search code examples
c++singletoncpp-core-guidelinesglobal-object

Why GitHub C++ Core Guideline says that global object better than singleton?


The Github C++ Core Guidelines say:

A global object is often better than a singleton.

I always thought the opposite. Something has changed since then in the C++? Or may be it's just another typo?


Solution

  • This is the rationale for avoiding singletons from the same guideline collection:

    I.3: Avoid singletons

    Reason

    Singletons are basically complicated global objects in disguise.

    Example

    class Singleton {
        // ... lots of stuff to ensure that only one Singleton object is created,
        // that it is initialized properly, etc.
    };
    

    There are many variants of the singleton idea. That's part of the problem.

    My analysis of the intentions of the author:

    Simpler is better. If disguising global objects in singletons doesn't solve the problems of global objects - like the guideline above implies - then there is no use in complicating the code by the use of the disguise.