Keeping a list of instances and garbage-collection

Simon TRENY simon.treny at free.fr
Sun Mar 29 13:33:13 PDT 2009


Hello,

I have a class "A" and I'd like to keep a list of all the created instances of this class. To do that, I have a static List!(A) in the A class and, in the constructor, I add each new instance to this list. This gives me the following code:

class A {
   private static List!(A) s_instances;

   public this() {
      s_instances.add(this);
   }

   public ~this() {
      s_instances.remove(this);
   }

   public static void printAll() {
      foreach (A instance; s_instances)
         print(instance.toString());
   }
}

But then, since all the instances are referenced by the static list, they are never garbage-collected, which could be a problem. In some other languages, this can be solved using weak references, but I haven't found any informations about using weak references in D. Is there any way to solve this problem?

Thanks,
Simon




More information about the Digitalmars-d mailing list