質問

Possible Duplicate:
Pass by reference more expensive than pass by value

I want to know which is better, sending parameters by value or by reference in C++. I heard that there are cases where sending by value is faster than sending by reference. Which are these cases?

Thanks

役に立ちましたか?

解決

As a general rule, you should pass POD types by value and complex types by const reference.

That said, a good place where you pass complex types by value is where you would need a copy of the object inside the function anyway. In that case, you have two choices:

  • pass the argument as a const reference and create a local copy inside the function

  • pass the argument by value (the compiler creates the local copy).

The second option is generally more efficient. For an example, see the copy&swap idiom.

他のヒント

The obvious case is when the parameter is equal to or smaller than a pointer in size and trivial to copy -- then you would pass by value. However, this is a age-old discussion and quite a long answer is required to answer it correctly for a given architecture. There are also many corner cases (e.g. RVO).

There's more to the question than speed -- semantics should be your first priority.

See also: Is it better in C++ to pass by value or pass by constant reference?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top