Question

Is there a need performance-wise for inline functions to pass its arguments by const reference like

foo(const T & a, const T &b)

compared to by value

foo(T a, T b)

if I don't change the values of a and b in the function? Does C++11 change recommend anything specific here?

Était-ce utile?

La solution

Pass by value can only elide the copy-constructor call if the argument is a temporary.

Passing primitive types by const reference will have no cost when the function is inlined. But passing a complex lvalue by value will impose a potentially expensive copy constructor call. So prefer to pass by const reference (if aliasing is not a problem).

Autres conseils

Theoretically the ones without reference might be copied in memory as there is the possibility that your inline function might be modifying them (even if it actually doesn't).

In many cases the compiler is smart enough to pick out that kind of thing but it will depend on the compiler and the optimization settings. Also if your function call on any non-const member functions in the class variables then your compiler will have to be smart enough to check if they are modifying anything as well.

By using a const reference you can basically give it a fairly clear indication.

EDIT: I just to a look at the machine code for a simple test program compiled with GCC 4.6 in ddd. The generated code seemed identical so it does seem to be optimized out. It's still good practice though for other compilers and if nothing else give a clear indication of the code's intent. It's also possible there are more complex situations that the compiler can't optimize though.

Also the llvm online dissembler demo shows identical bitcode is generated there too. If you turn off optimization it is slightly longer without the const reference.
* 1964 bytes - No const reference (and no other consts on functions/paramaters)
* 1960 bytes - Just no const reference but other consts.
* 1856 bytes - With consts and const reference.

Pass by reference is faster than by value depending on data type.
However for inline functions the function body (and thus all references / passed in values) are added to the line of code they are used in anyway so technically there are no variables being passed around, only more lines of code in the same area.

reference http://www.cprogramming.com/tutorial/lesson13.html

There is also a very helpful answer under the question should-i-take-arguments-to-inline-functions-by-reference-or-value

  • Example may have been misleading, removed -
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top