0

Trying to clear my understanding when move happens, and when it's better to write functions that pass values by value, instead of reference, to gain from moves.

void foo()
{
  std::string localStr;
//
  foo1(localStr);
}
void foo1(const std::string str)
{

}

Will in this case localStr be moved into foo1?

And if to add one more level of functions call:

void foo()
{
  std::string localStr;
//
  foo1(localStr);
  //localStrisn't used anymore
}
void foo1(const std::string str)
{
   foo2(str);
   //str isn't used anymore
}
void foo2(const std::string str)
{
}

Will there be two moves?

Bruice
  • 543
  • 3
  • 11
  • There are no *moves* being performed in this code at all. Both examples are making *copies* instead. A *move* would look more like this: `foo1(std::move(localStr));` (`foo2(std::move(str));` would not be valid since `str` is `const` and so can't be moved from). – Remy Lebeau Mar 03 '21 at 18:43
  • Note that you may get "move-like" behaviour if the compiler determines that it can get away with it without anyone noticing. See the [As-if Rule](https://en.cppreference.com/w/cpp/language/as_if). – user4581301 Mar 03 '21 at 18:47

1 Answers1

0

You pass a copy of str by value. It's not moved. If you use a pointer or reference only an address is copied.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38