How to use destroy and free.
Salih Dincer
salihdb at hotmail.com
Mon Apr 25 00:26:41 UTC 2022
On Sunday, 24 April 2022 at 21:00:50 UTC, Alain De Vod wrote:
> Is this a correct program to explicit call destroy & free ?
>
> ```
> void main(){
> int[] i=new int[10000];
> import object: destroy;
> destroy(i);
> import core.memory: GC;
> GC.free(GC.addrOf(cast(void *)(i.ptr)));
> }
> ```
Yes, first destroy() then free()...
```d
import std.stdio;
import object: doDestroy = destroy;
import core.memory : MEM = GC;
void disposeOf(T)(T obj)
{
auto mem = cast(void*) obj;
scope (exit) MEM.free(mem);
doDestroy(obj);
}
void main()
{
int[] i = new int[1024];
i[$-1] = 41;
doDestroy(i);
MEM.free(i.ptr);
// You don't need to addrOf(cast(void*)i)
//i.length = 1024;
//assert(i[$-1] == 0);
//i[$-1].writeln(" am there?");
if (i !is null)
{
"still alive!".writeln;
disposeOf(i);
}
"bye...".writeln;
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list