Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | SG <s.gesemann@gmail.com> |
|---|---|
| Newsgroups | comp.std.c++ |
| Subject | Re: x = f(move(x)) |
| Date | 2011-09-10 00:30 -0700 |
| Organization | http://groups.google.com |
| Message-ID | <5565cb4b-e87c-4faf-8867-2968a3147ff2@o9g2000vbo.googlegroups.com> (permalink) |
| References | <8jV9q.191323$k33.95339@en-nntp-13.dc1.easynews.com> |
On 8 Sep., 23:47, Joe Gottman wrote:
>
> Suppose I have the following pair of functions:
>
> string foo(const string &x); // Makes a copy of x, modifies, and returns it.
> string foo(string &&x) // Modifies and returns x itself, since x is an rvalue.
>
> Given these functions, does the following code work?
>
> int main()
> {
> string x = "hello";
> x = foo(move(x));
> return 0;
> }
Yes. foo(move(x)) refers to some other temporary object. At this time,
x will be "empty" but it does not matter. x is still assignable.
> Of course, one way around this problem is to replace the line
> x = foo(move(x))
> with the two lines
> string temp = move(x);
> x = f(move(temp));
>
> This would work, but it is slightly unwieldy, requiring a temporary
> variable and two calls to move. It would be nice if there were a
> library function [...]
Let me stop you right there. As I said, there is no problem with your
1st code example. But I would like to suggest an alternative:
string foo(string x) { // no other overloads needed!
std::reverse(x.begin(),x.end());
return x;
}
:
string z = ...;
z = foo(move(z)); // x and foo(move(z)) will be move-constructed
automatically
The nice thing about move-enabled classes is that you don't need to
sprinkle rvalue references all over the place. x in foo and the
function's return value will automatically be move-constructed. Pass-
by-value should become more fashionable again in my opinion. Be sure
to check out Dave's "Want Speed? Pass by value!" article:
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Cheers!
SG
--
[ comp.std.c++ is moderated. To submit articles, try posting with your ]
[ newsreader. If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Back to comp.std.c++ | Previous | Next — Previous in thread | Find similar
x = f(move(x)) Joe Gottman <josephgottman@comcast.net> - 2011-09-08 14:47 -0700 Re: x = f(move(x)) Daniel Krügler <daniel.kruegler@googlemail.com> - 2011-09-10 00:30 -0700 Re: x = f(move(x)) SG <s.gesemann@gmail.com> - 2011-09-10 00:30 -0700
csiph-web