www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Memory reference that does not stop garbage collection.

reply Jonathan Levi <catanscout gmail.com> writes:
I have observers and listeners.

class Observer {
    Listener[] listeners;
}
class Listener {}

The observers keep references to listeners, but I would like the 
GC to garbage collect listeners even if observers have references 
to it and remove the references in observers.

I should be able to use `core.memory.GC.removeRange` right?

class Observer {
   Listener[] listeners;
   this() {
     listeners = [];
     GC.removeRange(listeners.ptr);
   }
}

And in the deconstructor for listeners release the references in 
observers.
How does that work if the listeners array gets reallocated when 
extending, do I just recall `removeRange` any time after an 
append?

I am guessing I am not the first one to want this so I would 
rather not reinvent the wheel myself.  I also do not want memory 
leaks.

Thanks!
Feb 08 2019
parent Rene Zwanenburg <renezwanenburg gmail.com> writes:
On Friday, 8 February 2019 at 15:42:13 UTC, Jonathan Levi wrote:
 I should be able to use `core.memory.GC.removeRange` right?
That would leave dangling references in the array. You may be interested in this, but I have not used it myself: https://repo.or.cz/w/iv.d.git/blob/HEAD:/weakref.d
Feb 08 2019