Boost logo

Boost :

Subject: Re: [boost] [operators] moving forward use return by reference for compilers with proper support?
From: Dave Abrahams (dave_at_[hidden])
Date: 2013-05-04 03:09:55

on Wed May 01 2013, Niall Douglas <> wrote:

>> Operators returning rvalue references are NOT safe. The C++98/03/11/14+
> rules
>> apply to this scenario:
>> X temporary();
>> const X& r = temporary(); // ok, lives as long as r does
>> X&& r2 = temporary(); // ok, lives as long as r2 does
>> They do NOT apply to this scenario:
>> X&& func(X&& x) { return std::move(x); }
>> const X& r3 = func(temporary()); // DANGLING REFERENCE
>> X&& r4 = func(temporary()); // DANGLING REFERENCE
>> The Standardization Committee made this mistake when applying rvalue
>> references to string's operator+(), which was fixed before C++11 was
> released.
> I completely agree. 99.9% of the time the only reason to *ever* return
> rvalue refs from an operator() is when you're passing through a
> parameter.

Even that's not safe.

> Otherwise, return by value and leave the compiler's optimizer do its job.

Just return by value :-)

Dave Abrahams

Boost list run by bdawes at, gregod at, cpdaniel at, john at