Answer to Question #24382 in C++ for Nourah

Question #24382
Why is constant call-by-reference often the best way to pass a struct-type value to a function?
1
Expert's answer
2013-02-18T08:32:28-0500
Pass by const reference

One of the major disadvantages of pass by value is that all arguments passed by value are copied to the parameters. When the arguments are large structures or classes, this can take a lot of time. References provide a way to avoid this penalty. When an argument is passed by reference, a reference is created to the actual argument (which takes minimal time) and no copying of values takes place. This allows us to pass large structures and classes with a minimum performance penalty.

However, this also opens us up to potential trouble. References allow the function to change the value of the argument, which in many cases is undesirable. If we know that a function should not change the value of an argument, but don’t want to pass by value, the best solution is to pass by const reference.

You already know that a const reference is a reference that does not allow the variable being referenced to be changed. Consequently, if we use a const reference as a parameter, we guarantee to the caller that the function will not (and can not) change the argument!

The following function will produce a compiler error:

1
2
3
4
void foo(const int &x)
{
x = 6;& // x is a const reference and can not be changed!
}
Using const is useful for several reasons:

It enlists the compilers help in ensuring values that shouldn’t be changed aren’t changed.
It tells the coder whether they need to worry about the function changing the value of the argument
It helps the coder debug incorrect values by telling the coder whether the function might be at fault or not
Rule: Always pass by const reference unless you need to change the value of the argument

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS