Okay, I’ve been reading about rvalues and they seem like a great idea, but something keeps bothering me about them. Particularly the claim that move allows us to steal resources and avoid copying.
I understand that move works and does avoid copying for everything that happens on the stack, but eventually most of the stuff done on the stack yields some value that we want copied into the heap and this is where I don’t think move works.
Assuming that int has a move assignment operator, given the following code:
struct Foo
{
int x;
};
void doIt()
{
Foo* f = new Foo();
f->x = (2 + 4);
}
So in this example, the rvalue resulting from (2+4) can supposedly be moved over to f->x instead of copied. Okay, great. But f and consequently f->x is on the heap and that rvalue is on the stack. It seems impossible to avoid a copy. You cannot simply point f->x to the memory of the rvalue. That rvalue is going to be blown away as soon as doIt ends. A copy seems necessary.
So am I right that a copy will be made?
Or am I wrong?
Or did I completely misunderstand the rvalue concept?
In this case, it probably would do a copy, but since the object only contains an
int, that’s not really much of a problem.The times you care are generally when the object contains a pointer to some data that’s allocated on the heap (regardless of where the object itself is allocated). In this case, avoiding allocating a new copy of that data is quite worthwhile (and since it’s on the heap even if the object itself is on the stack, you can move it regardless of where the object itself is located).