Dlang manual memory management

In the sweet spot between C & C++ , we have NIM, but also Dlang.
To install :
https://github.com/ldc-developers/ldc/releases/download/v1.42.0/ldc2-1.42.0-freebsd-x86_64.tar.xz

D program below will push a class instance on stack , this class instance will call constructor/destructor automatic when variable goes in and out of scope. The constructor/destructor will allocate/free memory on the heap.

cat test.d
Code:
// No garbage collection here.

import std.stdio:writefln,writeln;
import object: destroy;
import core.memory: GC;
import core.stdc.stdlib: malloc,free;
import std.typecons;

class C {
    int * pa;
    int [] a;
    // Constructor
    this() {
        writefln("Called constructor");
        // HEAP OBJECT
        pa=cast(int *)malloc(1000*int.sizeof);
        a=pa[0..1000];
    }
    ~this() {
        if (pa !is null) {
            free(pa);
            a = null;
            pa = null;
            writeln("Called destructor and freed memory");
        }
    }
}

void dofun() {
    // STACK OBJECT
    scope x=new C;
    x.a[3]=5;
    writefln("%12x",&x);
}

int main(){
    dofun();
    dofun();
    return 0;
}

To compile,
Code:
ldc2 --dip1000 --safe-stack-layout --boundscheck=on --D --g --w --de --d-debug test.d

More info to follow on UI develoment with GTK & WEB development with VIBE.D
 
Back
Top