代码中vector<int> temp_a = arr;处是否会触发移动语义?
问题解答
先看给出的代码片段:
void printArray(vector<int> arr) { vector<int> temp_a = arr; //<<------- move here? for(int i = 0; i < temp_a.size(); ++i) cout << temp_a[i] << endl; }
这一行不会触发移动操作,原因如下:
arr是函数的形参,是有明确名字的对象,属于左值。- C++里的移动构造函数仅在传入右值时才会被调用(右值包括临时对象,或者通过
std::move()强制转换的左值)。 - 当前代码里的
temp_a = arr调用的是vector的拷贝构造函数,会完整复制arr中的所有元素到temp_a中,不会转移资源。
如果想要触发移动操作,需要把代码改成这样:
vector<int> temp_a = std::move(arr);
std::move(arr)会把左值arr转换成右值引用,此时才会调用移动构造函数,将arr的内部资源直接转移给temp_a,避免拷贝开销。
内容的提问来源于stack exchange,提问作者Aa Aa
相关产品推荐
相关产品推荐

