Reference type demonstration
1 class C 2 { 3 struct Agg 4 { 5 static int dtorCount; 6 7 int x = 10; 8 ~this() { dtorCount++; } 9 } 10 11 static int dtorCount; 12 13 string s = "S"; 14 Agg a; 15 ~this() { dtorCount++; } 16 } 17 18 C c = new C(); 19 assert(c.dtorCount == 0); // destructor not yet called 20 assert(c.s == "S"); // initial state `c.s` is `"S"` 21 assert(c.a.dtorCount == 0); // destructor not yet called 22 assert(c.a.x == 10); // initial state `c.a.x` is `10` 23 c.s = "T"; 24 c.a.x = 30; 25 assert(c.s == "T"); // `c.s` is `"T"` 26 destroy(c); 27 assert(c.dtorCount == 1); // `c`'s destructor was called 28 assert(c.s == "S"); // `c.s` is back to its inital state, `"S"` 29 assert(c.a.dtorCount == 1); // `c.a`'s destructor was called 30 assert(c.a.x == 10); // `c.a.x` is back to its inital state, `10` 31 32 // check C++ classes work too! 33 extern (C++) class CPP 34 { 35 struct Agg 36 { 37 __gshared int dtorCount; 38 39 int x = 10; 40 ~this() { dtorCount++; } 41 } 42 43 __gshared int dtorCount; 44 45 string s = "S"; 46 Agg a; 47 ~this() { dtorCount++; } 48 } 49 50 CPP cpp = new CPP(); 51 assert(cpp.dtorCount == 0); // destructor not yet called 52 assert(cpp.s == "S"); // initial state `cpp.s` is `"S"` 53 assert(cpp.a.dtorCount == 0); // destructor not yet called 54 assert(cpp.a.x == 10); // initial state `cpp.a.x` is `10` 55 cpp.s = "T"; 56 cpp.a.x = 30; 57 assert(cpp.s == "T"); // `cpp.s` is `"T"` 58 destroy!false(cpp); // destroy without initialization 59 assert(cpp.dtorCount == 1); // `cpp`'s destructor was called 60 assert(cpp.s == "T"); // `cpp.s` is not initialized 61 assert(cpp.a.dtorCount == 1); // `cpp.a`'s destructor was called 62 assert(cpp.a.x == 30); // `cpp.a.x` is not initialized 63 destroy(cpp); 64 assert(cpp.dtorCount == 2); // `cpp`'s destructor was called again 65 assert(cpp.s == "S"); // `cpp.s` is back to its inital state, `"S"` 66 assert(cpp.a.dtorCount == 2); // `cpp.a`'s destructor was called again 67 assert(cpp.a.x == 10); // `cpp.a.x` is back to its inital state, `10`
Value type demonstration
int i; assert(i == 0); // `i`'s initial state is `0` i = 1; assert(i == 1); // `i` changed to `1` destroy!false(i); assert(i == 1); // `i` was not initialized destroy(i); assert(i == 0); // `i` is back to its initial state `0`
Destroys the given object and optionally resets to initial state. It's used to destroy an object, calling its destructor or finalizer so it no longer references any other objects. It does not initiate a GC cycle or free any GC memory. If initialize is supplied false, the object is considered invalid after destruction, and should not be referenced.