Mattias said:
Rickard said:
Okay, how do I know when I should [implement a function]
to pass a const reference and not a simple const?
I guess you mean when you should one of the following
(1) void foo(const A& a);
(2) void foo(const A a);
The second declaration is equivalent to
void foo(A a);
Identifier a is the *formal* argument.
When you invoke foo:
A a;
foo(a);
identifier a is the *actual* argument.
The compiler emits code to pass a by reference in the first case and
the compiler emits code to pass a by value in the second case.
It does *not* matter whether a is passed by value or const reference
as far as the program that invokes foo is concerned.
The only difference is that pass by reference doesn't require
the copy of the actual argument like pass by value.
This is an important optimization
only when a is larger than about one or two machine words.
My short answer to this would be:
it makes little sense to do something like (2).
Since you are passing your A object by value,
the [actual argument] you pass to foo() will be copied
[into the formal argument]
and there will be now way for foo() to alter [the actual argument].
Declaring 'foo(const A a)' doesn't tell users of foo()
anything more than if you would declare it 'foo(A a)'.
Using the const qualifier for formal arguments passed by value
is only useful in the function *definition*:
void foo(const A a) {
// The const qualifier informs the compiler that
// any attempt to modify a in the body of the function
// is a mistake and the compiler should issue a warning.
}