Keeping a list of instances and garbage-collection
Sergey Gromov
snake.scaly at gmail.com
Mon Mar 30 16:45:29 PDT 2009
Sun, 29 Mar 2009 17:42:48 -0400, Chad J wrote:
> 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
You can remove only something previously added. Since a static array is
not a root nor a range of roots, you can't make it invisible to GC this
way.
More information about the Digitalmars-d
mailing list