mainstr34m mainstr34m - 12 days ago 6
C++ Question

Assigning local std::vector to reference in C++

I am not sure if my approach is correct.
Since I am passing vector

v
by reference to
Function
, after it's execution vector's content will change.

What if I can't work directly on vector
v
and decide to use temporary vector
temp
. Is assigning to
v
my temporary through
v = temp
correct? Won't reference
v
point at some memory which will be swept after execution of
Function
?

void Function(std::vector<bool> &v) {
std::vector<bool> temp(v.size(), false);

// some operations on vector temp
// ...

v = temp;
}

Answer

Won't reference v point at some memory which will be swept after execution of Function?

No. For v = temp;, v is copy assigned from temp. Then v will contain the same content with temp, but it has nothing to do with temp; temp ia a local variable which will be destroyed later, but the argument passed in won't be affected.

BTW: Since temp is a local variable which will be destroyed when get out of the function, copying from it will be waste. You could move from it:

v = std::move(temp);
Comments