What is the role of passing by reference when you are not modifying the variables?

Whether these links (&) are simply a memory-saving problem or idioms, or is there a reason that such statements like these use links when transferring through a copy, would do the same.

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

or object declaration, for example:

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

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

+4
source share
3 answers

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

+8
source

. , .

, .

+4

, ( ) ( ). , , .

In your first example, the function is a template, and since we do not know that the cost, or, in fact, the ability, of the copy that follows the link, is the only reasonable choice. Since this is a template function, it is almost certainly built-in when the call can be optimized, in particular if it Tis a small object.

0
source

All Articles