views:

446

answers:

4

Hello everyone, this question has been bugging me for a while, so i thought i'd ask.

Is there a case where pass-by-reference is more expensive than pass-by-value in C++? If so, what would that case be?

Thanks.

+3  A: 

Yes, accessing a passed by reference argument might require more levels of indirection than a passed by value argument. Besides, it's may to be slower if the size of the argument is smaller than the size of a single pointer. Of course, it's all assuming the compiler is not optimizing it.

Mehrdad Afshari
+9  A: 

Prefer passing primitive types (int, char, float, ...) and POD structs that are cheap to copy (Point, complex) by value.

This will be more efficient than the indirection required when passing by reference.

See Boost's Call Traits.

The template class call_traits<T> encapsulates the "best" method to pass a parameter of some type T to or from a function, and consists of a collection of typedefs defined as in the table below. The purpose of call_traits is to ensure that problems like "references to references" never occur, and that parameters are passed in the most efficient manner possible.

Gregory Pakosz
+3  A: 

You can read this article "Want speed ? Pass by value" about copy elision and RVO ( Return by Value Optimization ). It explains that references sometimes prevent the compiler from doing them.

fa.
A: 

The compiler could optimize passing a primitive type by reference to simply passing by value, if the type is the same size or smaller than the size of a reference/pointer. There's no guarantee the compiler will do this, so if you have a choice, pass primitive types by value. In templated code though, you often have to pass by reference anyway - consider vector's push_back which takes a const reference. If you have a vector of ints, you'd be passing a reference to a primitive type. In that situation, you'd hope the compiler would optimise that by substituting the reference with a value. Since the vector could be storing large types though, accepting a const reference is the best choice.

AshleysBrain
"The compiler could optimize... " as long as the callee doesn't modify the referand, or read it after calling any code that might modify it. But of course in cases where it does, you hopefully wouldn't be asking the question "which is more expensive", rather "which is correct" :-) The awkward ones are cases where you think the compiler can optimize, but actually it can't because you've overlooked some reason it must be a reference (aliasing rules being the prime cause of surprises).
Steve Jessop