1

Consider the following snippet:

class Bar {...};
class Foo {
  public:
    Foo(const Bar& bar): bar_(bar) {}
  private:
    Bar bar_;
};

int main() {
    Foo foo({...});  // Passing an rvalue Bar object here.
}

Question: will the object that I have generated be copied in the Foo's constructor, or will it be moved? More precisely, which of the following is true?

  • It will be copied always.
  • It will be moved always (I'm pretty sure it is not the case).
  • This is unspecified behavior.

1 Answer 1

4

It will be copied always.

The rvalue you create binds to a const lvalue reference. But even if it was bound to an rvalue reference, you construct bar_(bar) from an lvalue (bar). The value category of the object that is bound to the reference is moot, what matters is the value category of the reference itself. And like already mentioned, the expression bar is an lvalue.

As a general and somewhat coarse rule of thumb, every expression that is a name of something is an lvalue.

If you want to support both moves and copies in one constructor, the way to go forward is this:

Foo(Bar bar): bar_(std::move(bar)) {}

Now bar can be constructed by either a move of a copy, depending on the source, and your member is constructed from an object you can safely move out of. This of course always incurs an extra move. If you want to avoid it, then two c'tors are required:

Foo(const Bar& bar): bar_(bar) {}
Foo(Bar&& bar): bar_(std::move(bar)) {}
3
  • That's what I expected. But isn't this one of those situations where it's safe to do the move instead of the copy, in general? I kinda hoped that modern compilers could do this optimization for me, allowing me to keep a (IMO more readable) const reference form and not sacrifice performance. But that would make this unspecified behavior, of course. So you are saying that this is fixed in the standard and copy can never be replaced with move here, right? Commented Dec 20, 2017 at 11:22
  • @SolenodonParadoxus - It's not safer. The move is done locally, in the c'tor. But the argument doesn't have to bind to an rvalue (the object is outside the function). Think separate compilation. You link an object with you c'tor (that assumes it's only fed rvalues). And then do this: Bar b; Foo f(b);. It's legal C++. You can't make it be not legal. Commented Dec 20, 2017 at 11:25
  • @SolenodonParadoxus - And yes, a copy is a copy. If we want a move, then we need to spell out a move. Commented Dec 20, 2017 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.