aa.remove in a destructor

Jonathan M Davis jmdavisProg at gmx.com
Sun Jun 24 04:51:52 PDT 2012


On Sunday, June 24, 2012 11:53:37 Dmitry Olshansky wrote:
> On 24-Jun-12 08:15, Ellery Newcomer wrote:
> > this code:
> > 
> > class X{
> > 
> >      string[string] s;
> >      this() {
> >      
> >          s["s"] = "S";
> >      
> >      }
> >      ~this() {
> >      
> >          s.remove("s");
> >      
> >      }
> > 
> > }
> > 
> > void main() {
> > 
> >      X x = new X();
> > 
> > }
> > 
> > produces this:
> > 
> > core.exception.InvalidMemoryOperationError
> > 
> > because the aa is calling gc_free during a collection, apparently.
> > 
> > Should I be expecting the above code to run without error or not?
> > 
> > thanks
> 
> I think no, as any with operation involving GC. For instance while you
> are removing elements table may decide to rehash itself and that means
> it may trigger allocation.

Basically, you should never do anything in a class' destructor/finalizer which 
could ever trigger the GC in any way. If that's going to be a problem, then 
you need to do whatever you're doing differently. Really, class 
destructor/finalizers are for managing resources which _aren't_ memory-related 
or involve memory which is not from the GC heap.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list