For anything larger than a 64 bit integer, why would I want to pass by value?
[Update] The question was closed, because it was not specific enough. One comment suggested that I specify a language. I deliberately did not do that, thinking that this site should be language agnostic.
I was prompted to ask this when I was linting some C++ 14 code this morning and was warned that a parameter was being passed by value.
C++ is syntactically interesting because the reference operator sort of blurs the difference between pass by value and pass by reference.
In C, if my function prototype is void foo(hugeStruct x)
then I am passing a huge structure by value and one can be aware of the passing mechanism by looking at the the calling code. If I want pass by reference, the function signature changes to void foo(hugeStruct* x)
and the call changes from foo(myHugeStruct)
to foo(&myHugeStruct)
.
In C++, the protoypes are void foo(hugeStruct x)
and void foo(hugeStruct& x)
but you can't determine the the passing mechanism by looking at the the calling code, which, in both cases, is foo(myHugeStruct)
.
In the case that I found this morning, the calling code was - inadvertently - passing a 256k array, by value. To answer @JMekker's comment
This isn't the 90's, passing parameters to functions has basically zero performance impact.
If that 256k array were passed by value then all 256k of it would be pushed on to the stack (as opposed to pushing only its address when passing by reference) which well cause a stack overflow, especially in the embedded world.
So, please correct any mistakes that I made, and tell me if there is ever a legitimate reason for me to want to pass large data structures by value.