Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...