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;
}
Won't reference
v
point at some memory which will be swept after execution ofFunction
?
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);
Yes, assigning v = temp is safe. For further information look at eg: https://isocpp.org/wiki/faq/references#overview-refs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.