按分配给const引用的值返回 [英] return by value assigned to const reference
本文介绍了按分配给const引用的值返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在修复某些代码中的另一个错误,并遇到了一些我认为是错误的代码;但是,此代码在gcc 4.4、4.5和4.6下进行编译,并且看起来像预期的功能。谁能告诉我这是否是有效的c ++?
I was fixing another bug in some code and came across some code that I would have thought was a bug; however, this code compiles under gcc 4.4, 4.5, and 4.6 and appears to function as "expected". Can anyone tell me if this is valid c++?
struct foo {
int bar;
};
foo myfunction(foo const &orig) {
foo fooOnStack = orig;
fooOnStack.bar *= 100;
return fooOnStack;
}
void myOtherFunction(foo const &orig) {
foo const &retFoo = myfunction();
// perhaps do some tests on retFoo.bar ...
}
如果这是有效的c ++,是否有人知道这是合法的?
If this is valid c++, does anyone know the rationale behind this being legal?
推荐答案
是的,这是合法的C ++。对临时对象形成对const的引用可将临时对象的生存期延长至引用的生存期。
Yes, this is legal C++. Forming a reference-to-const to a temporary extends the lifetime of the temporary to the lifetime of the reference.
这篇关于按分配给const引用的值返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文