On 2/21/21 9:29 PM, Preetpal wrote:
I want to restrict a D application to a single instance. Is there a way to do this using the D standard library?

When you say "application", you mean a class or type?

If so, you can do this:

class C
{
   private this() { /*ctor code for single instance */ }
   private static C _instance = new C();
   public C instance() { return _instance; }
}

You can also do it with a struct, but it's not as bullet-proof:

struct S
{
  @disable this();
  private static S _instance;
  ref S instance() { return _instance; }
}

But one can always do this, and the compiler will never prevent it:

S s = S.init;

All these have an instance per thread.

If you want a global singleton that is initialized on first use, use the D singleton pattern: https://wiki.dlang.org/Low-Lock_Singleton_Pattern

-Steve

Reply via email to