Skip to content

Latest commit

 

History

History
103 lines (66 loc) · 2.03 KB

File metadata and controls

103 lines (66 loc) · 2.03 KB

When to use std::move()

When to use std::move() on move-only types

When it doesn't compile without it.

Say, image is a move-only image class:

Code std::move() needed?

gatherImage = std::move(camera->capturePicture());

NO

functionTakesImage(std::move(camera->capturePicture()));

NO

image_t image;
...
return std::move(image);

NO

functionTakesImage(std::move(gatherImage));

Yes!

What's the difference? In the last case the image had a name, which, importantly, means you might refer to it later, so, to be sure about your intent, you need std::move().

In the other cases, the image did not have a name (or, in the return case, had a name that was going out of scope), so there was no (or, well, very little beyond convoluted code) way to reference the image after the move, so moving is "safe" here, and the default.

For experts

temporaries, xvalues, prvalues, blah blah blah.

Basically...

Use std::move() on move-only types when it doesn't compile without it.

Assume you don't need std::move(). Just write like you were using an int. Add the std::move() when it doesn't compile, and then look at what the compiler is trying to tell you, and whether that thing is OK to be moved (ie consider what happens to the moved-from object afterward - is that OK?).

Yeah, but what about std::vector?

What about types that are not move-only?

Well, now that we have a feel for when you would use std::move() on move-only objects, apply that mostly to copyable objects. Use std::move() when you don't need the data over here any more, and want it over there. Same general rules:

  • consider what happens to the moved-from object afterward - is that OK?
  • when you return a local vector from a function, you don't need std::move() - the compiler will do a better job without it.