|
Boost : |
Subject: Re: [boost] [operators] moving forward use return by reference for compilers with proper support?
From: Stephan T. Lavavej (stl_at_[hidden])
Date: 2013-04-30 20:08:32
[Andrew Ho]
> They referred me to http://www.open-
> std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf (draft of C++ standard),
> which in section 12.2, clause 5 says that a temporary's lifetime is extended
> to the lifetime of the reference it is bound to. I checked draft n3376
> (latest publicly available draft as of today), and the same clause was
> present.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf is the current Working Paper.
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.
Stephan T. Lavavej
Visual C++ Libraries Developer
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk