C++’s Simple Singletons

The singleton is one of the most controversial design patterns. Yet,  it is omnipresent in many real-world code bases. With C++ 11,   creating a thread safe, lazy initialized singleton  is  cheap, painless and straight forward process, by either using local statics or std::call_once:

Local statics

Creating a singleton with a local statics boils down to:

Singleton& Singleton::Instance()
{
	static Singleton instance;
	return instance;
}

The standard guarantees the Singleton instance  is created once, even if more than one thread attempts to call Instance at the same time (ISO/IEC 14882:2011 6.7 footnote #4)

call_once

std::call_once wraps a callable object and ensure it is called only once. Even if multiple threads try to call it at the same time.

The wrapper is using an object of type std::once_flag to keep track whether the code was already called:

#include <iostream>
#include <mutex>

class Singleton
{
private:
	Singleton(const Singleton&) = delete;
	Singleton & operator=(const Singleton&) = delete;
	

	static std::unique_ptr<Singleton> instance;
	static std::once_flag onceFlag;
public:
	Singleton() = default;

	static void NofityInit()
	{
		std::cout << "Initializing Singleton" << '\n';
	}
	static Singleton& Singleton::Instance()
	{
		std::call_once(Singleton::onceFlag,[] (){
			NofityInit();
			instance.reset(new Singleton); 
		});

		std::cout << "Getting  Singleton instance" << '\n';
		return *(instance.get());
	}
};

std::unique_ptr<Singleton> Singleton::instance;
std::once_flag Singleton::onceFlag;

int main()
{
	Singleton& s1 = Singleton::Instance();
	Singleton& s2 = Singleton::Instance();

	return 0;
}

The output for this program:


Initializing Singleton
Getting Singleton instance
Getting Singleton instance

For more details, including performance study, check out Rainer Grimm’s in-depth post.