www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 17246] New: Extra destructor call.

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

          Issue ID: 17246
           Summary: Extra destructor call.
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: critical
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: japplegame gmail.com

import std.stdio;
struct Foo {
    int val;
    this(int val) {
        writefln("%s.this(int)", val);
        this.val = val;
    }
    this(this) {
        writefln("%s.this(this)", val);
        this.val = val;
    }
    ~this() {
        writefln("%s.~this()", val);
        this.val = val;
    }
}
struct Bar {
    Foo foo;
    this(Foo foo, bool) { this.foo = foo; }
}

bool fun(bool val) { return !val; }

auto genBar(bool flag) {
    return flag ? Bar() : Bar(Foo(10), fun(!flag));
}

void main(string[] args) {
    auto bar = genBar(args.length == 0);
}

Compiler generates extra destructor call:

10.this(int)
10.this(this)
10.~this()
10.~this()
10.~this()

If we slightly change function genBar:
auto genBar(bool flag) {
    auto a = flag ? Bar() : Bar(Foo(10), fun(!flag));
    return a;
}

or

auto genBar(bool flag) {
    return flag ? Bar() : Bar(Foo(10), false);
}

then output looks as expected:

10.this(int)
10.this(this)
10.~this()
10.~this()

--
Mar 08 2017