Keeping a list of instances and garbage-collection

Chad J gamerchad at __spam.is.bad__gmail.com
Sun Mar 29 14:42:48 PDT 2009


Simon TRENY wrote:
> 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
> 

Maybe what you are looking for are the GC.removeRoot or GC.removeRange
functions which are available in both Phobos and Tango?
http://www.dsource.org/projects/tango/docs/current/tango.core.Memory.html
http://www.digitalmars.com/d/2.0/phobos/std_gc.html
http://www.digitalmars.com/d/1.0/phobos/std_gc.html



More information about the Digitalmars-d mailing list