Consider the following code
struct Ri {
int& i;
};
auto do_something() {
int v{2};
return Ri{v};
}
Why is this allowed to compile?
It should be possible to infer that the scope of the returned Ri object is that of the caller. Why is it allowed to be created with a reference to a variable with the local scope?
Is there a legitimate use case for this?
Because there is nothing in the standard that says it shouldn't.
In this particular case, yes. But in general things may not be so simple.
Here is one example:
What should the compiler do in this case?
vwent out of scope, butgthat it referred to is still in scope. So, now the compiler has to keep track of the scope of the assigned value? Multiply number of variables by number of assignments and things may start getting a bit hairy.Here is another example:
In this case the compiler has no way of knowing lifetime of the value returned by
get_v(). So, what do we do now?UPDATE:
You/compiler can't assume that the scope of the value returned by
get_v()extends to the translation unit, eg:I don't think so.