graphicsMan
graphicsMan

Reputation: 402

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 retFoo.bar ...
}

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

Upvotes: 19

Views: 6207

Answers (2)

pups
pups

Reputation: 92

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.

Upvotes: -1

PlasmaHH
PlasmaHH

Reputation: 16046

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.

Upvotes: 33

Related Questions