How to use destroy and free.

Ali Çehreli acehreli at yahoo.com
Wed May 4 12:57:26 UTC 2022


On 5/3/22 22:37, forkit wrote:

 > In any case, I disagree that caring about when memory gets deallocted
 > means you shouldn't be using GC. (or did I get that one wrong too??)

At least I don't agree with you there. :) Yes, one should not care about 
how memory gets freed if one did not care how that memory was allocated.

 > You can have the best of both worlds, surely (and easily).

There are always many subtleties.

 > This (example from first post):
 >
 > void main(){
 >      int[] i = new int[10000];
 >
 >      import object: destroy;
 >      destroy(i);
 >      import core.memory: GC;
 >      GC.free(GC.addrOf(cast(void *)(i.ptr)));
 > }

So is this about that simplest case?

1) We know the number of elements up front.

2) The elements are simple like 'int' that there is no separate 
allocation for each?

If so, I don't think adding a language feature is necessary for this 
narrow case.

Note: To answer a related question: I haven't designed or implemented 
any language, haven't contributed to any compiler, etc. I have no strong 
say on D or any other language. I am just a user who disagrees with the 
request in this thread.

 > could (in theory) be replaced with this:
 >
 > void main(){
 >      inscope int[] i = new int[10000];
 >
 >      // inscope means 2 things:
 >      // (1) i cannot be referenced anywhere except within this scope.
 >      // (2) i *will* be GC'd when this scope ends

If this feature was for more complicated examples as well, i.e. if we 
added new elements ever, there might be multiple memory allocations by 
the GC. Are we concerned only about the very last one? So, allocations 
0, 1, .. N-1 can be left to the GC but allocation N must be freed now?

If not, should the GC keep a list of allocations for each 'inscope' 
object? (Is this only for arrays? What about potentially multiple 
allocations for a single object throughout its lifetime?)

What about that list itself? :) Should that be allocated from the GC and 
be 'inscope' as well?

There must be other questions that I miss. What I am sure is, somebody 
in the future will be unhappy how 'inscope' is implemented for their 
case and will propose another feature on top of it. I think it is better 
to leave such special decisions to the programmer.

Again though, I would be happy to be corrected.

Ali



More information about the Digitalmars-d-learn mailing list