Rvalue references - The resolution
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Mon May 6 08:31:05 PDT 2013
On 5/6/13 11:12 AM, Steven Schveighoffer wrote:
>> If x > 100, the code is saving a reference to a destroyed temporary.
>> If you couldn't see it, how many do you expect would see similar
>> issues in even simpler and cleaner D code?
>
> No, I was wondering whether the compiler detects this and keeps the
> temporary in scope (after all, it is in control of that temporary's
> lifetime).
It can't.
Consider the body of min isn't known (eliminate templates etc). Then
what the compiler sees is a function call that returns a const ref. All
it can assume is it's a valid reference which it will subsequently bind
to the name given by the caller. The reference will refer therefore to a
destroyed rvalue (temporaries are destroyed at the end of the full
expression).
Your example is irrelevant to this discussion because returning an
rvalue and subsequently binding it to a const T& is a completely
different scenario. It would be also sound if it weren't for this:
struct A {
A(const T& x) : a(x) {}
const T& a;
};
In _this_ case, initializing A with an rvalue of type T compiles and
subsequently runs with undefined behavior.
I repeat: binding rvalues to ref would make every mistake C++ has done
in the area, and add a few original ones. It is not a simple problem; if
it seems, more study is required.
Andrei
More information about the Digitalmars-d
mailing list