I have been having some confusion on the reference in C++, so I did a little experiment with the following function
std::vector<float> & fun(std::vector<float> & x) {
return x;
}
Then I call the function using the following two ways:
std::vector<float> x(10000);
std::vector<float> result1 = fun(x);
std::vector<float> & result2 = fun(x);
Now the variable result2 is indeed a reference of x, but result1 seems to be a copy of x instead of a reference. So here I am confused:
Why can I declare a non-reference variable to be the return value of a function that returns a reference?
Does C++ changes my returned reference to a non-reference variable because my declaration of result1 is not a reference?
std::vectoraccepts a (const) reference. That operator does a deep copy.