0

I just found some code in Boost paraphrased as the following:

class A {};

class B {
public:
  B(A a): a_(std::move(a)) {}
private:
  A a_;
};

int main() {
  A a;
  B b(std::move(a));
}

Assuming this works, why use move constructor/assignment with an rvalue reference? Or does a move constructor/assignment just save you the trouble of a second std::move() call?

  • 1
    Because the *actual* Boost.Move code is not your "paraphrased" version. – Nicol Bolas Oct 04 '19 at 14:54
  • I don't understand what you mean with "why use move constructor/assignment with an rvalue reference". There is no move constructor and no assignment here (and no rvalue reference variable either). – Max Langhof Oct 04 '19 at 14:57
  • `move constructor/assignment` are for the class itself, not it's parameters. This is a quick way to take any type of `A` and get a copy+move or move+move. The performance isn't the best, but you only have to write a single line of code to get OK performance. – NathanOliver Oct 04 '19 at 14:58
  • If you tried to do this with an actual constructor, you would have a circular logic problem where you define the construct in terms of itself. – François Andrieux Oct 04 '19 at 14:58
  • 1
    I think OP ask why having `B(A a): a_(std::move(a)) {}` instead of `B(A&& a): a_(std::move(a)) {}`. – Jarod42 Oct 04 '19 at 15:02
  • Are you calling `B(A a)` a move constructor? Or are you saying that since `B(A a)`, move constructors/assignments should work with non-reference paramters too? – HolyBlackCat Oct 04 '19 at 15:03

2 Answers2

0

C++ move constructors without rvalue references?

B(A) is not a move constructor. It is a converting constructor.

Assuming this works

This converting constructor does work.

why use move constructor/assignment with an rvalue reference?

Because you cannot have a move constructor/assignment without an rvalue reference.

In case you meant to ask, why use rvalue reference converting constructor: It can avoid one move construction. The downside of that is needing an additional overload for lvalue references in case you want to be able to copy from those.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

My "paraphrased" code actually comes from the code referenced by this question so my question had already been asked and answered.