Foreach statement (without braces '{}') and scoping objects, prevents the call to the object's destructor. The code below outlines the problem.
Code
----
module main;
import std.stdio;
class MyClass {
public:
this() {
writefln("Constructor");
}
~this() {
writefln("Destructor");
}
private:
int myNumber;
};
int main() {
writefln("1 - Start: OK dtor called");
foreach (a; new int[1]) {
scope x = new MyClass;
}
writefln("1 - End: OK dtor called\n");
writefln("2 - Start: dtor NOT called");
foreach (a; new int[1])
scope x = new MyClass;
writefln("2 - End: dtor NOT called\n");
return 0;
};
Output
------
1 - Start: OK dtor called
Constructor
Destructor
1 - End: OK dtor called
2 - Start: dtor NOT called
Constructor
2 - End: dtor NOT called
Comment #1 by clugdbug — 2009-09-10T14:17:41Z
This was fixed in DMD2.032 (probably a side-effect of the fix for bug 2925).