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:
void ByValue(MyClass obj) {
(void)printf(“ByValue called..\n”);
}
/* 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’.
myObject - Constructor called.
Calling 'ByValue'
unnamed object - Copy Constructor called.
ByValue called..
unnamed object - Destructor called.
myObject - Destructor called.
We know that constructors (whether they are copy constructors or not), assignment operators and destructors can be costly operations.
Let's see what happens when we pass ‘MyClass’ by reference to the function:
void ByReference(MyClass &obj) {
(void)printf(“ByReference called..\n”);
}
/* 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.
Next: Const-Correctness >>
More C++ Articles
More By J. Nakamura