Thursday, August 17, 2017

Fully lazy singleton in C++/CLI

Today I was trying to implement in C++/CLI the equivalent of the sixth Singleton pattern as shown here.

I liked the idea of using the Lazy class as it is fully lazy, and thread-safe, and very clear and simple.

I couldn't find any examples of anyone else doing it, so I gave it a go.  It took me a few minutes, but I was finally able to get it working:

ref class Singleton
{
public:
    static property Singleton^ Instance
    {
        Singleton^ get() { return m_lazy_instance->Value; }
    }

private:
    Singleton(); // Implemented in cpp

    static Singleton^ CreateInstance() { return gcnew Singleton(); }
    static System::Lazy^ m_lazy_instance = gcnew System::Lazy(gcnew System::Func(CreateInstance));
};


The secret was knowing to pass in a gcnew System::Func delegate to the System::Lazy constructor.

Note that if you naively create a System::Lazy using just the default constructor, it will compile but you will get an Exception at runtime because the Singleton constructor is private.

1 comment:

  1. yes! working!

    static SingleT^ CreateInstance()
    {
    return gcnew SingleT();
    }
    static Lazy^ lazyIns = gcnew Lazy(gcnew System::Func(CreateInstance));

    ReplyDelete