On Wednesday, 21 December 2016 at 15:01:20 UTC, Eugene Wissner wrote:
On Wednesday, 21 December 2016 at 14:15:06 UTC, John C wrote:
On Wednesday, 21 December 2016 at 11:45:18 UTC, Eugene Wissner wrote:
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?

Possibly to do with named return value optimisation.

Isn't an optimization that changes the behavior bad? I had a crash in the code where the destructor did something meaningfull, freed the memory (the same pointer) twice.

Basic stuff such as this is appropriately tested. The named return value optimization is enforced by D (incl. unoptimized builds), so behavior doesn't change by this optimization. It's you who changed the behavior by removing the if. Due to the `if`, the compiler doesn't know whether it should construct `a` or `b` directly into the memory (sret pointee) provided by the caller. When omitting the `if`, it's clear that `b` is returned in all cases, so the compiles constructs `a` on the local stack (and destructs it before exiting the function), but emplaces `b` into `*sret` (i.e., the caller's stack) and can thus elide 1x postblit + 1x dtor.

Reply via email to