我不确定我的做法是否正确。
因为我通过引用 Function
来传递 vector v
,所以在它执行之后 vector 的内容将会改变。
如果我不能直接在 vector v
上工作并决定使用临时 vector temp
怎么办。通过 v = temp
分配给 v
我的临时值是否正确?不会引用 v
指向执行 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
?
没有。对于 v = temp;
,v
是从 temp
复制分配的。则v
会包含与temp
相同的内容,但与temp
无关; temp
是一个本地对象,稍后会被销毁,但传入的参数不会受到影响。
顺便说一句:由于 temp
是一个本地对象,当退出函数时将被销毁,从中复制可能效率低下。你可以离开它:
v = std::move(temp);
关于c++ - 将本地 std::vector 分配给 C++ 中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40759858/