On Jon's site he has thisvery elegantly designed singleton in C# that looks like this:
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
I was wondering how one would code the equivalent in C++? I have this but I am not sure if it actually has the same functionality as the one from Jon. (BTW this is just a Friday exercise, not needed for anything particular).
class Nested;
class Singleton
{
public:
Singleton() {;}
static Singleton& Instance() { return Nested::instance(); }
class Nested
{
public:
Nested() {;}
static Singleton& instance() { static Singleton inst; return inst; }
};
};
...
Singleton S = Singleton::Instance();
This technique was introduced by University of Maryland Computer Science researcher Bill Pugh and has been in use in Java circles for a long time. I think what I see here is a C# variant of Bill's original Java implementation. It does not make sense in a C++ context as the current C++ standard is agnostic on parallelism. The whole idea is based on the language guarantee that the inner class will be loaded only at the instance of first use, in a thread safe manner. This does not apply to C++. (Also see this Wikipedia entry)
You'll find a great discussion of how to implement a singleton, along with thread-safety in C++ in this paper.
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
As far as I am aware, inheritable Singleton behaviour is not possible in C++ or Java, (or at least it wasn't on earlier versions of JDK). This is a C# specific trick. Your subclasses will have to explicitly implement the protocol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With