-1

I am interested to know when the arguments of a function are copied.

#include <vector>

void foo (std::vector<float> a)
{
   std::vector<float> y = std::move(a);
   //do something with vector y
}

int main()
{
   std::vector<float> x {1.0f, 2.0f, 3.0f};
   std::cout << x.at(0) << " " << x.at(1) << " " << x.at(2) << std::endl; //1.0 2.0 3.0
   foo(x);
   std::cout << x.at(0) << " " << x.at(1) << " " << x.at(2) << std::endl; //print nothing
}

Does the function copy its argument from the start? If not, how do we know when the arguments are copied? From the above code, I assume that the arguments are not copied because std::move still affects variable x.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • `//print nothing` -- No, this is not correct. I'm not sure how you are running this, but [when I run it, `x` is not changed](http://coliru.stacked-crooked.com/a/d88915cdbac670ac). – cdhowie Jul 30 '20 at 21:25

1 Answers1

3

Does the function copy its argument from the start?

The a argument is copied at the call site within main(), before the body of foo() is entered.

From the above code, I assume that the arguments are not copied because std::move still affects variable x.

The a argument is being passed by value, so a makes a copy of x. Then foo() move's the copy into y. x is un-affected, which is the opposite of your claim.

If the a argument were passed by reference instead, or you move'd x into a, then x would be affected.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770