C++ singleton vs. global static object

Solution 1:

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.

Solution 2:

In C++, the order of instantiation of static objects in different compilation units is undefined. Thus it's possible for one global to reference another which is not constructed, blowing up your program. The singleton pattern removes this problem by tying construction to a static member function or free function.

There's a decent summary here.

Solution 3:

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. static global object won't...but then I wasn't sure..because this in C++.. (I was coming from C#)

A static global object can have state in C# as well:

class myclass {
 // can have state
 // ...
 public static myclass m = new myclass(); // globally accessible static instance, which can have state
}

What are the advantages one over the other? (in C++)

A singleton cripples your code, a global static instance does not. There are countless questions on SO about the problems with singletons already. Here's one, and another, or another.

In short, a singleton gives you two things:

  • a globally accessible object, and
  • a guarantee that only one instance can be created.

If we want just the first point, we should create a globally accessible object. And why would we ever want the second? We don't know in advance how our code may be used in the future, so why nail it down and remove what may be useful functionality? We're usually wrong when we predict that "I'll only need one instance". And there's a big difference between "I'll only need one instance" (correct answer is then to create one instance), and "the application can't under any circumstances run correctly if more than one instance is created. It will crash, format the user's harddrive and publish sensitive data on the internet" (the answer here is then: Most likely your app is broken, but if it isn't, then yes, a singleton is what you need)