You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:22:33