Comment #0 by andrej.mitrovich — 2013-10-23T07:10:52Z
-----
module test;
import std.exception;
import std.stdio;
class C
{
this()
{
s = S(1);
}
S s;
}
struct S
{
this(int x)
{
_x = x;
int f;
if (!f) throw new Exception("");
}
~this()
{
stderr.writefln("S dtor -- _x: %s", _x);
}
int _x = -1;
}
void main()
{
// S dtor not called (ok, because its ctor failed)
assertThrown!Exception(S(1));
// S dtor called even though S object was not
// properly initialized (ctor failed)
assertThrown!Exception(new C());
}
-----
The S object is left in an improperly-initialized state since its ctor failed (due to the thrown Exception), but for some reason its dtor /is/ called, however only in a situation when it's nested in a class.
Comment #1 by k.hara.pg — 2015-06-25T03:27:50Z
(In reply to Andrej Mitrovic from comment #0)
> but for some reason its dtor /is/
> called, however only in a situation when it's nested in a class.
The dtor is called from druntime during process finalization.
By inserting a print line at the end of main, you can confirm that.
void main()
{
//// S dtor not called (ok, because its ctor failed)
//assertThrown!Exception(S(1));
// S dtor called even though S object was not
// properly initialized (ctor failed)
assertThrown!Exception(new C());
stderr.writeln("end main");
}
Prints:
$ dmd -run test
end main
S dtor -- _x: 1
Comment #2 by robert.schadek — 2024-12-13T18:13:16Z