Scholar
Scholar

Reputation: 293

What is the role of passing by reference when you do not modify variables?

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?

Upvotes: 4

Views: 553

Answers (3)

Walter
Walter

Reputation: 45434

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.

Upvotes: 0

mcwyrm
mcwyrm

Reputation: 1693

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.

Upvotes: 4

Dale Wilson
Dale Wilson

Reputation: 9434

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)

Upvotes: 8

Related Questions