On Wednesday, 21 December 2016 at 12:32:51 UTC, Nicholas Wilson
wrote:
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.
Why if the "if block" is removed, the code prints "Destruct" only
two times. One because "a" goes out of scope and one in the main
function. I don't understand, why "if (false) ..." changes the
behavior