returning struct, destructor
Nicholas Wilson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Dec 21 04:32:51 PST 2016
On Wednesday, 21 December 2016 at 11:45:18 UTC, Eugene Wissner
wrote:
> Consider we have a function that returns a struct. So for
> example:
>
> import std.stdio;
>
> struct A {
> ~this() {
> writeln("Destruct");
> }
> }
>
> A myFunc() {
> auto a = A(), b = A();
> if (false) {
> return a;
> }
> return b;
> }
>
> void main() {
> myFunc();
> }
>
> This prints 3 times "Destruct" with dmd 0.072.1. If I remove
> the if block, it prints "Destruct" only 2 times - the behavior
> I'm expecting. Why?
> Thx
Structs are value types, so unless they you pass them by
pointer/reference, they get copied.
in myFunc it prints "Destruct" twice, one for a and once for b.
In main it prints it one more for the (discarded) A returned from
myfunc.
More information about the Digitalmars-d-learn
mailing list