Why would you pass an object by value in C++

c++, calling-convention

Solution

The question of when passing by value might be better than by const reference has different answers with different versions of the standard.

In the good old C++03, and a few years ago, the recommendation would be to pass anything that does not fit in a register by const reference. In this case, the answer would be:

- Because `Obj` fits in a register and passing by value and passing by value will be more efficient

Still in C++03, in the last years (absurd as it seems some articles recommended this almost 10 years back, but there was no real consensus),

- if the function needs to make a copy, then doing so in the interface allows the compiler to perform copy-elision if the source for the copy is a temporary, so it can be more efficient.

With the approval of the new C++11 standard, and increasing compiler support for rvalue-references, in many cases even when the copy cannot be elided, and again

- if the function needs to make a copy, even when the copy cannot be elided, and for types that support it, the contents will be moved (in common jargon the object will be moved, but it is only the contents that get shifted), which again will be more efficient than copying internally.

As of the question of why the two different calling conventions, they have different goals. Passing by value allows the function to modify the state of the argument without interfering with the source object. Additionally, the state of the source object will not interfere with the function either (consider a multithreaded environment, and a thread modifying the source while the function is still executing).

Problem

Possible Duplicate: Is it better in C++ to pass by value or pass by constant reference? I'm aware of the differences of passing by value, pointer and reference in C++, and I'd consider passing objects by value (instead of const reference) in C++ to be almost always a programming error. ``` void foo(Obj o); ... // Bad void foo(const Obj &o); ... // Better ``` The only case I can think of where it might be appropriate to pass by value instead of const reference is where the object is smaller than a reference, and passing by value is therefore more efficient. But, surely this is the sort of thing that compilers are built to determine? Why does C++ actually need pass by value AND pass by const reference, and - are compilers allowed to automatically convert the call to (and from) a const reference if appropriate? (There seem to be 100s of C++ calling convention question, asking about the differences between (say) value and reference - but I couldn't find one that asked "why?".)

Original source

Related problems