Re: [boost] [operators] moving forward use return by reference for compilers with proper support?
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. Otherwise, return by value and leave the compiler's optimizer do its job. Niall --- Opinions expressed here are my own and do not necessarily represent those of BlackBerry Inc.
on Wed May 01 2013, Niall Douglas
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
participants (2)
-
Dave Abrahams
-
Niall Douglas