How to use destroy and free.

Ali Çehreli acehreli at yahoo.com
Mon Apr 25 01:59:34 UTC 2022


On 4/24/22 14:00, Alain De Vod wrote:
 > Is this a correct program to explicit call destroy & free ?

destroy() is called with the object that you want its destructor to be 
executed on. This is very rare in D because when the destructor has to 
be called, one relies on the lifetime of a struct object, or uses 
scope(exit), scope(success), or scope(failure).

free is called on memory that you explicitly allocated.

 > ```
 > void main(){
 >      int[] i=new int[10000];
 >      import object: destroy;
 >      destroy(i);

That does not have any effect for an int array because int does not have 
any destructor.

Assuming you are asking for struct elements, let me try:

import std.stdio;

struct S {
   ~this() {
     writeln(__FUNCTION__);
   }
}

void main() {
   auto arr = [ S() ];
   writeln("calling destroy");
   destroy(arr);
   writeln("called destroy");
   writeln("leaving main");
}

No, destroy'in an array does not call the destructor of the elements:

calling destroy  <-- No destructor called here
called destroy
leaving main
deneme.S.~this

And that is expected because arrays don't have destructors. If you want 
to destroy the elements of an array, you must call destroy for each 
element. One way:

   import std.algorithm : each;
   arr.each!((ref e) => destroy(e));

Now the output has our destructor call:

calling destroy
deneme.S.~this
called destroy  <-- HERE
leaving main
deneme.S.~this

The final destructor is called for the .init state of the element 
because destroy() blits the .init state on objects.

 >      import core.memory: GC;
 >      GC.free(GC.addrOf(cast(void *)(i.ptr)));

That is wrong because you did not allocate that address yourself.

It is further wrong for arrays in general because there may be slices to 
arrays, which you would not free the elements of.

Ali



More information about the Digitalmars-d-learn mailing list