4

Are these references(&) just an issue of saving memory or idioms or is there a reason to why statements like these use references when passing by copy would accomplish the same thing.

template <class T>
bool testGreater (const T& one, const T& two);

or an object declaration such as this:

Cars BMW (const Engine&); //where engine is a class

What is the function of passing by reference when you do not need to modify the item passed?

Scholar
  • 293
  • 3
  • 8
  • 16
  • 1
    It's for performance. Passing by const reference means the object doesn't have to be copied. That can be significant for big objects. I case of a function template you cannot know what type T is, so using `const T&` as parameter is a safe bet. – Tobias Brandt Nov 13 '13 at 20:25
  • 1
    It also allows you to pass the value of a non-copyable object – IdeaHat Nov 13 '13 at 20:26
  • Imagine if the Engine class would contain some integers, floats, some strings, etc...you would have to carry a lot of information when you pass by value. Instead, passing by reference, you only pass some kind of an address where all this information can be found... – DrM Nov 13 '13 at 20:31
  • Duplicates: [here](http://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference?rq=1) and [here](http://stackoverflow.com/questions/4986341/where-should-i-prefer-pass-by-reference-or-pass-by-value) – JBentley Nov 13 '13 at 20:53

3 Answers3

8

When you pass by value you must make a copy of the object. Depending on what object is used to instantiate the template, this can be expensive. (or impossible. Some objects are not copyable)

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
  • Best overall answer as it mentions non-copyable objects, and doesn't try to claim that passing by reference is always faster. – JBentley Nov 13 '13 at 20:52
4

Instances of complex types are typically passed by reference to save on overhead. It is much cheaper to pass a pointer than to recreate an entire data structure.

This is true whether you intend to modify the object or not.

mcwyrm
  • 1,571
  • 1
  • 15
  • 27
0

Passing by reference works always, as it does not need to call the copy constructor (which may not exist) and requires no new object (in the body of the function). However, it is not always faster, for example for small types.

In your first example, the function is a template and as we don't know the cost, or in fact possibility, of a copy, passing by reference is the only sensible choice. As this is a template function, it is almost certainly inlined, when the call may well be optimised away, in particular if T is a small object.

Walter
  • 44,150
  • 20
  • 113
  • 196