开发者

return by value assigned to const reference

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 ret开发者_运维知识库Foo.bar ...
}

If this is valid c++, does anyone know the rationale behind this being legal?


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.


I think you still need to be careful. I have a case where g++-4.9 with C++11 and complicated Eigen types does not respect this (it deletes data in the returned temporary even though its lifetime is supposed to be extended). Hence, even though it might be legal it should be flagged as dodgy unless there is a really good reason for it.

Also, given C++11 MUST allocate the temporary at the call site if returned by value its usefulness is perhaps less than it used to be if you are using the latest standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜