Better Singletons with shared_ptr

Long time no post! I’ve been busy working on my game engine recently and some school work (sigh.) but, anyway! I am back at it again (hopefully).

Recently I have stumbled upon an interesting problem. The static (de)construction order fiasco. The problem is that, before you actually see this madness in action, you have no idea how important it is to consider it in design of a new system!

So, the problem: A.cpp and B.cpp both define statics:

Type& GetSingleton() {
    static Type _instance;
    return _instance;
}

But what happens if A.obj (object file of A.cpp) uses the static in B.obj and B.obj gets destructed first? well hell happens as it did at my work! It was one of the worst types of bugs I have ever tracked.

The naive solution of course, is not to use Singletons! as many people would say it. But I am not on that camp and I’d say Singletons have their use. So here is my solution to this problem:

#include <memory> // std::shared_ptr

template< class T >
struct Singleton {
    // Handle is a ref-counted type of the instance
    using Handle = std::shared_ptr< T >;

    // Returns a Handle to instance
    Handle GetInstance() {
        static Handle inst{ std::make_shared<T>() };
        return inst;
    }
}

What happens is that, when you call Singleton::GetInstance(), you get a ref-counted std::shared_ptr in return. Therefore, each module that needs access to this Singleton can store it like:

// File: A.cpp
#include "A.hpp"

namespace {
auto INSTANCE = Singleton<Type>::GetInstance();
}

// ... rest of the file.

This way, life-time of the Singleton is guaranteed for object file’s lifetime and also it is constructed on first use! It’s a win-win situation.

Invisible ink with Javascript

		 	  			 			 			 		 		 	  				  				 	  			   	 		 		  		  	 	 	     ink 	     is 	     		 			 		 							 	   	     dead. 	     you 	     		 	 	 			 	 				  					 	   	     can 	     		 			 		 							 	   	     see 	     it.

I was just too bored today at school and remembered a trick one of my friends showed me a while ago. Remember the citrus ink trick that blew your mind back in elementary school (probably)? Well you can do it in Javascript too!

In the box above there’s a hidden message. If you copy it ENTIRELY, you can paste it in the text area below to reveal its message.

Message with invisible ink: You may type to decode

Revealed message: You may type to encode

 


But how does it work?

Easy! If you have a message (string), you can convert each of its characters to its binary encoded equivalent. For example m: m in ASCII table is 1101101. If you replace all its 0’s with spaces and 1’s with tab characters, you get yourself some invisible m!

Fun part of it is that you can totally write:

/ 	     /.replace(/\s{7}/g, function(c) {
    String.fromCharCode(
        parseInt(
            c.replace(/ /g,'0')
            .replace(/	/g,'1')
        ,2));
});

To decode an invisible m. It converts back all spaces to 0’s and all tabs to 1’s using fromCharCode.
Everything between forward slashes is of type RegExp (/ /, v8 actually just logs a plain object when asked to invoke typeof //).

C++ Indexed Singleton – a more complete Singleton template wrapper

Just looking for the source code? Get it here!Github

I occasionally end up using Singletons in my code, not very often of course. I find Singletons to be very cute! For things like Loggers or Game Engine instances they are just the perfect architecture. Just imagine writing scripting bindings for a Game Engine which its engine instance is not accessible through a Singleton.

Anyway, anybody has an opinion around Singletons but that is not the idea of this post. I am going to present my own Singleton template wrapper in this post which I think is more complete than the original implementation.

The original thread-safe Singleton template wrapper is implemented like this:

template<typename T>
struct Singleton
{
	// get the instance of the singleton.
	static T& get()
	{
		// static allocation is thread-safe.
		// no need for synchronizing.
		static T instance;
		return instance;
	}
};

Nothing special about it. It creates a local static of the type you passed to it and you can get a reference to that static instance via get() method. For example:

// Defining a class
class MyClass
{
public:
	MyClass();
	void do_stuff();
}

// Using the Singleton wrapper to access -
// - a single global instance of the class:
auto& ref = Singleton<MyClass>::get();
ref.do_stuff();

But I had a different issue, rather a challenge to myself I should say. What if I want to have more than one singleton of the same type?

Well at the first glance; it can be impossible. Either Singleton needs to be named differently or there needs to be two distinct types for the compiler.

Here’s how I solved this challenge.

template<typename T, int index>
struct ProxyStorage
{
	T mStorage;

	// optionally index can be stored as well.
	/* enum { mIndex = index }; */
};

That’s what I call a proxy type. What happens is that ProxyStorage is really not a new type. It produces a proxy to the passed type; convoluted with an index parameter. What does that mean? That means:

ProxyStorage<MyClass, 0> instance0;
// and
ProxyStorage<MyClass, 1> instance1;

Are essentially the same things but to your compiler they are different types! We can take advantage of this trick and finish our Singleton wrapper implementation:

template<typename T, int i = 0>
struct Singleton
{
	// get the indexed instance of the singleton.
	static T& get()
	{
		// static allocation is thread-safe.
		//no need for synchronizing.
		static ProxyStorage<T, i> instance;
		return instance.mStorage;
	}
};

Now this wrapper can be used to hold more than one instance of a single type in Singletons:

// instance with index 0
Singleton<MyClass, 0>::get();
// instance with index 1, different than index 0
Singleton<MyClass, 1>::get();

Need the source code? Get it here!Github

If you cannot fix it, feature it.

-Dr. Campbell, Portland State University