Static Arrays: Behaviour of Passing & Returning

Simen Kjærås simen.kjaras at gmail.com
Wed Mar 21 12:15:13 UTC 2018


On Wednesday, 21 March 2018 at 12:01:01 UTC, Quantum Nerd wrote:
> How is it possible that b in main() and r in the function 
> occupy the same memory?
> I would expect the same behaviour as with c.
>
> Can somebody with more experience shed some light on this?

I'm pretty sure you're seeing NRVO - Named Return Value 
Optimization. Also called copy elision:
https://en.wikipedia.org/wiki/Copy_elision

The compiler sees that when you return r, it's immediately 
assigned to b. Since it's a waste of cycles to allocate twice and 
copy the values, the function is told where the result will end 
up, and writes it there immediately.

The reason you don't see that with c is that the compiler isn't 
very smart, especially not with optimizations turned off, so it 
doesn't know for sure that it can safely overwrite the values 
already in c at that point.

--
   Simen


More information about the Digitalmars-d-learn mailing list