@
robgeek
I hope you don't mind this discussion continuing in this fashion: I have kinda derailed your topic a bit; but hopefully you already have your answer. I can start a new Topic if you want :+)
@
dhayden
Thanks for your reply, I understand the reference / alias part now.
Do you mean that caller should destroy the value when it goes out of scope? |
I guess all the following argument / discussion is a bit academic: the answer is to return a const reference (or return the object), but here goes anyway .....
I hadn't thought of static variables, I wonder if that is the reason for an almost blanket rule?
As the link the
Moschops kindly provided says that the scope is extended when a const reference is returned, it seems it can be done in that situation. The rule is:
gotw wrote: |
---|
A2: No.
The "const" is important. The first line is an error and the code won’t compile portably with this reference to non-const, because f() returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const. |
Emphasis mine. I wonder
why that is the rule? Also, the xvalue has a name: that makes it a lvalue doesn't it? This article was written in 2008, before the more refined concepts of lvalue, xvalue, prvalue and the categories of glvalue and rvalue were introduced, although I understand this is still the rule.
So if the scope is extended for const reference, and we can have RVO, copy elision, move semantics for an object: why not for a non const reference ?
Moschops was saying he wouldn't be surprised if that it allows the compiler to skip some checks and allow optimisations, it's just that RVO etcetera are optimisations.
Maybe the const reference is an elegant solution that avoids the static variable problem, but the corollary is that local non const refs can't be returned ? I haven't seen it described in this way.