Say I have a proc returning a complex data structure. A common idiom in C would be to allocate space for the data in the calling function, and pass a pointer to that as an out parameter, so that the callee can build the result directly there, and no copying is necessary when returning.
I think I read this is done implicitly in Nim, so that for instance the following
proc callee(x: int): BigDataStructure =
for i in 0 .. x:
result[i] = something(i)
proc caller(): auto =
let b = callee(5)
would have callee fill the memory allocated by the declaration of b, which is on the stack frame of caller (or on the heap).
Is this understanding correct? Does this feature depend on using the result implicit variable or would it be the same if I created another variable to hold the result and return that?
By using an intermediate variable that you then return, you introduce an intermediate copy, because return tmp means basically result = tmp; return. Backends may still be able to optimize it away, but it can't be guaranteed.
proc callee(): Foo = expression
any different from this?
proc callee(): Foo =
result = expression
I tend to prefer the first style when usable, since it looks much more declarative, but I would not want to inadvertently introduce a copy