Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between reference and const reference as function parameter?

Tags:

c++

reference

Here is a simple snippet of C++ code:

A foo(){
  A a; // create a local A object
  return a;
}

void bar(const A & a_r){

}

bar(foo());

Why does the argument of function bar have to be a const reference,not just a reference?

Edit1: I know that reference is to avoid copying overhead. and const is for read-only. But here I have to make it a const reference, otherwise if I remove the "const", g++ will throw an error to me.

Edit2: My guess is that the return object of foo() is a temporary object, and it's not allowed to change the value of a temporary object ?

like image 427
wei Avatar asked Nov 12 '09 04:11

wei


1 Answers

Without the error message, I'm not exactly sure what the compiler might be complaining about, but I can explain the reason logically:

In the line:

bar(foo()); 

The return value of foo() is a temporary A; it is created by the call to foo(), and then destructed as soon as bar() returns. Performing a non-const operation (i.e. an operation that changes the temporary A) doesn't make sense, as the object A is destructed right afterwards.

Looking a little more, this is a virtual dup of this question:

How come a non-const reference cannot bind to a temporary object?

which has an excellent answer.

like image 168
gdunbar Avatar answered Oct 06 '22 02:10

gdunbar