Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code Jon Skeet's Singleton in C++?

Tags:

c++

c#

singleton

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();
like image 844
AndersK Avatar asked Oct 30 '09 08:10

AndersK


3 Answers

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)

like image 109
Vijay Mathew Avatar answered Oct 16 '22 14:10

Vijay Mathew


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

like image 45
navigator Avatar answered Oct 16 '22 14:10

navigator


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.

like image 1
ConcernedOfTunbridgeWells Avatar answered Oct 16 '22 14:10

ConcernedOfTunbridgeWells