引用和const引用之间的差异作为函数参数? [英] Difference between reference and const reference as function parameter?
问题描述
这里是一个简单的C ++代码片段:
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());
为什么函数bar的参数必须是一个const引用,而不仅仅是一个引用?
Why does the argument of function bar have to be a const reference,not just a reference?
Edit1:我知道引用是为了避免复制开销。和const是只读的。但这里我必须使它成为一个const引用,否则如果我删除const,g ++会给我一个错误。
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:我的猜测是返回对象foo()是一个临时对象,不允许更改临时对象的值?
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:
在行:
bar(foo());
foo()的返回值是一个临时A;它是通过调用foo()创建的,然后一旦bar()返回就被销毁。执行非const操作(即更改临时A的操作)没有意义,因为对象A将在之后被销毁。
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:
http://stackoverflow.com/questions/1565600/non-const-reference-to-temporary-object
其中优秀的答案。
这篇关于引用和const引用之间的差异作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!