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
};
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.
yes! working!
ReplyDeletestatic SingleT^ CreateInstance()
{
return gcnew SingleT();
}
static Lazy^ lazyIns = gcnew Lazy(gcnew System::Func(CreateInstance));