Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer
As you know, in programming C++, it is much better to return a reference to an object than it is to return that object by value. As we will see in this article, it is also much better to pass a function parameter by reference than it is to pass it by value. But there are exceptions to this, as Jun Nakamura explains.
Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer - To pass or not to pass by value (Page 2 of 6 )
By default, function parameters are passed by value. This means that the compiler creates a copy of the original object that was passed to the function and introduces the copy to the function as its parameter. The easiest way to visualize this is to use the MyClass class from the previous article and try the following test code:
/* in main() */ MyClass obj(“myObject”); (void)printf(“Calling ‘ByValue’\n”); ByValue(obj);
Clearly we can see the copy constructor being called to copy ‘myObject’ into the function parameter ‘obj’ in order to expose it to the function ‘ByValue’.
/* in main() */ MyClass obj(“myObject”); (void)printf(“Calling ‘ByReference’\n”);
No copy constructors were called… most excellent!
Calling 'ByReference' ByReference called..
Just like returning an object by reference, passing one by reference to a function allows you to keep working with the object itself, instead of instanced copies. This is much more efficient, since no new objects have to be created nor destroyed.
The only time it is less efficient to pass a reference instead of a value is when you are working with primitive values like integers, floats, booleans, and so on. In these cases a reference causes unnecessary overhead. References are almost always implemented like pointers; so passing a primitive value directly is more efficient than passing the address to that value.