Another solution to the Singleton pattern in C++

So, while working on the Kwarqs robotics code, I found a useful solution to implementing the singleton pattern in c++ that I believe avoids the static initialization fiasco (with a small restriction) *and* doesn’t leak memory.

What I’ve created is a template class that takes a pointer to a pointer at construction, and deletes the pointer as it is getting destructed. While you cannot guarantee when the class is created due to static initialization issues, from what I can see the C++ standard does guarantee that all intrinsics are initialized before other items are constructed. By using a pointer to a pointer, we can guarantee that the location of the object will be the same (and thus destruction will happen correctly), and provided we initialize the static variable to NULL we can also guarantee that initialization will happen correctly.

Warning: A key assumption made by this class is that the static object is only accessed during the normal scope of the program — ie, the object that this class contains a pointer to a pointer to should not be accessed by anything that could be called after main() is complete. For some code bases, this can be very tricky to enforce.

Usage of the class is quite trivial:

SomeType * SomeType::m_instance = NULL;
StaticDeleter someTypeDeleter(&m_instance);

// example singleton initialization
SomeType * SomeType::GetInstance()
	if (SomeType::m_instance == NULL)
		SomeType::m_instance = new SomeType();
	return SomeType::m_instance;

And the implementation of the static deleter is also quite trivial (but I’ve provided a downloadable version as well), check it out:

// (C) 2009 Dustin Spicuzza, released under modified BSD license

class StaticDeleter {

    StaticDeleter(TypeToDelete ** ptr2ptr) :

        if (*m_ptr2ptr)
            delete *m_ptr2ptr;

    TypeToDelete ** m_ptr2ptr;

Download it now

Leave a Reply