4

When passing primitive types like int or float, is it wasted effort to write something like this:

foo(const float&);

rather than just passing by value:

foo(float);
  • 1
    possible duplicate of [Passing scalar types by value or reference: does it matter?](http://stackoverflow.com/questions/20982042/passing-scalar-types-by-value-or-reference-does-it-matter) – Mgetz Jan 12 '14 at 18:14

4 Answers4

3

For floats? Yes, pretty much.

There's simply nothing to gain here: floats are small and the copy will not be slower than the creation of a pointer to implement the reference.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

It depends on the implementation of references. As per Standard (§8.3.2/4):

It is unspecified whether or not a reference requires storage (3.7).

references could, theoretically, save you from the copy of the float. That, of course, will be vain if references are implemented as pointers. Therefore the answer is implementation dependent.

Most of the time this kind of micro-optimizations don't make much sense. I highly doubt the bottle neck of your application is in the copy of that float.

Shoe
  • 74,840
  • 36
  • 166
  • 272
1

Keep in mind that pass-by-value may in some cases enable a broader spectrum of compiler optimizations. Chandler Carruth (of Clang fame) spoke on some of the difficulties optimizing compilers face when dealing with references/pointers to objects in his keynote at C++ Now 2013.

Ron Jones
  • 11
  • 1
0

When passing primitive types like float, it doesn't help anything to pass by const reference. Passing by value accomplishes pretty much the same thing - any change made to the value of the parameter will not affect the value in the calling function (if calling by value) - no change can be made to the parameter (if calling by const reference).

With classes, however, passing a const class reference would be much more efficient than passing it by value (which would have to make a copy of the object).

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47