D vs nim

Shachar Shemesh shachar at weka.io
Thu Mar 29 09:45:04 UTC 2018


On 28/03/18 02:23, Timothee Cour wrote:
> that comment was regarding -betterC
> RAII (with structs) has been available in D for a while, eg:
> 
> ```d
> struct A{
>    ~this(){...}
> }
> 
> void fun(){
>    A a; // when a goes out of scope, will call dtor deterministically
> }
> ```
> 

Not so long as destructors don't reliably run.

$ dmd --version
DMD64 D Compiler v2.079.0
Copyright (C) 1999-2018 by The D Language Foundation, All Rights 
Reserved written by Walter Bright

$ cat test.d
import std.stdio;

struct A {
     int a;

     this(int a) {
         this.a = a;

         writefln("A(%s) constructed", a);
     }

     ~this() {
         writefln("A(%s) destructed", a);
     }
}

struct B {
     A a;

     this(int val) {
         a = A(val);
         throw new Exception("Constructor failed");
     }
}

void main() {
     try {
         auto a = A(1);
         auto b = B(2);
     } catch(Exception ex) {
         writefln("Caught: %s", ex.msg);
     }
}

$ rdmd test.d
A(1) constructed
A(2) constructed
A(1) destructed
Caught: Constructor failed

https://issues.dlang.org/show_bug.cgi?id=14246


More information about the Digitalmars-d mailing list