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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With