Double arguments and moving semantic

Assuming I have the following function foo:

Widget foo(Widget lhs, Widget rhs) {
  return lhs.bar(rhs);
}

Then I want to use it with the same argument on both sides:

Widget baz(Widget w) {
  return foo(w, w);
}

It so happened that the widget is large, and I would like to avoid too many copies. Assuming the bar is in place, I could do the following:

Widget baz(Widget w) {
  return foo(std::move(w), w);
}

This will make only one copy. But I'm afraid that this is the wrong code, because the order in which the arguments were passed is not specified in C ++, and I can give the argument with drag and drop.

Instead, I do the following:

Widget baz(Widget w) {
  Widget w_bis(w);
  return foo(std::move(w), std::move(w_bis));
}

Am I too careful? Is there an easier way to achieve this?

Notes. The design foois that I can write expressions more naturally, enjoying the benefits of copying. t = foo(foo(x,y), foo(std::move(t),z))will make only 3 necessary copies.

+4
1

Let say, bar is an in-place function that I would like to transform into a more classical mathematical operator (side-effect free), , operator+ operator+=:

foo, rhs const , lhs:

Widget foo(Widget lhs, const Widget& rhs)
{
  return lhs.bar(rhs);
}

baz " ".

0

Source: https://habr.com/ru/post/1668017/


All Articles