开发者

Pass by reference more expensive than pass by value

开发者 https://www.devze.com 2022-12-17 10:21 出处:网络
Is there a case where pass-by-reference is more expensive than pass-by-value in C++? If开发者_JS百科 so, what would that case be?Prefer passing primitive types (int, char, float, ...) and POD structs

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


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消