Destructor order
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Oct 22 11:03:44 PDT 2014
On Wednesday, 22 October 2014 at 15:45:02 UTC, eles wrote:
> D version:
>
> { //displays ~A~B~C
> A foo = scoped!(A)();
> B bar = scoped!(B)();
> C caz = new C();
> destroy(caz);
> }
>
> Why the objects are not destroyed in the inverse order of their
> creation? Case in point, destroying foo releases a lock for bar
> and caz.
`foo` should be a `Scoped!A`. When it's typed as `A`, the
`Scoped!A` that is returned by `scoped`, is destructed
immediately (and the reference leaks, I guess).
Compare:
import std.stdio;
import std.typecons;
class A {~this() {writeln("~A");}}
class B {~this() {writeln("~B");}}
class C {~this() {writeln("~C");}}
void main()
{
{
writeln("bad:");
A foo = scoped!(A)();
writeln("1");
B bar = scoped!(B)();
writeln("2");
}
{
writeln("good:");
auto foo = scoped!(A)();
writeln("1");
auto bar = scoped!(B)();
writeln("2");
}
}
prints:
bad:
~A
1
~B
2
good:
1
2
~B
~A
More information about the Digitalmars-d-learn
mailing list