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

Viewed 3906

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?".)

6 Answers
Related