C++0x: returning rvalue references, recycling temporaries
[split from thread "std::max(unsigned, size_t), amd64 and C++0x"]
On 11 Sep., 10:59, Howard Hinnant <howard.hinn...@gmail.com> wrote:
On Sep 9, 6:28 pm, SG <s.gesem...@gmail.com> wrote:
There's some benefit to returning rvalue references: temporary objects
can be recycled:
string operator+(const string&, const string&);
string && operator+(string &&, const string &);
string && operator+(const string &, string &&);
string && operator+(string &&, string &&);
(operator+ overloads example, see document N1377)
string x = "/home/foo/" + get_string() + ".png"; // is fine
string && result = "/home/foo/" + get_string() + ".png";
but I guess this [...] would result in a dangling reference. [...]
Defining a reference and initializing it by an _rvalue reference
returned by a function_ is doomed to fail, isn't it?
I consider this a bug in the rvalue-ref papers. :-)
What exactly? The line of code ("string && result = ...") is not part
of document N1377. The reason I brought this up was because I'm not
sure about its intended semantics w.r.t. the temporary's life time.
I'm currently assuming that it's not ill-formed but usually unsafe
because such a function most likely returns a reference to a temporary
(function argument T&&). But I really like the idea of recycling
temporary objects. I'd appreciate it if you could share your thoughts
on this.
A& f(A& x) { return x; } // #1
A&& f(A&& x) { return x; } // #2
A a = f(A()); // #2 OK
A&& b = A(); // -- OK
A&& c = f(b); // #1 OK
A&& c = f(A()); // #2 Ouch!
Cheers,
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]