Let\'s say I want to implement a function that is supposed to process an object and return a new (possibly changed) object. I would like to do this as efficient as possible in C
None of the functions you show will have any significant return value optimizations on their return values.
makeChanges
returns an Object&
. Therefore, it must be copied into a value, since you're returning it. So the first two will always make a copy of the value to be returned. In terms of the number of copies, the first one makes two copies (one for the parameter, one for the return value). The second one makes two copies (one explicitly in the function, one for the return value.
The third one shouldn't even compile, since you can't implicitly convert an l-value reference into an r-value reference.
So really, don't do this. If you want to pass an object, and modify it in-situ, then just do this:
Object &process1(Object &arg) { return arg.makeChanges(); }
This modifies the provided object. No copying or anything. Granted, one might wonder why process1
isn't a member function or something, but that doesn't matter.