这里会有一次移动吗?

huangapple go评论89阅读模式
英文:

Will there be a move here

问题

这里是简化后的代码片段:

void printArray(vector<int> arr)
{
    vector<int> temp_a = arr; // <<------- 移动到这里?
    for (int i = 0; i < temp_a.size(); ++i)
        cout << temp_a[i] << endl;
}

那里会发生移动吗?

英文:

Here is simplified code snippet:

void printArray(vector&lt;int&gt; arr)
{
    vector&lt;int&gt; temp_a = arr; //&lt;&lt;------- move here?
    for(int i = 0; i &lt; temp_a.size(); ++i)
    	cout &lt;&lt; temp_a[i] &lt;&lt; endl;
}

Will there be a move there?

答案1

得分: 2

不,std::vector 的移动构造函数不会在那种情况下被使用;相反,将使用复制构造函数。

一般来说,移动不会隐式发生,因为由标识符(未限定标识符)构成的每个表达式都是左值(例如,arr 是左值)。移动构造函数接受 std::vector&& 的右值引用,而它不能绑定到左值。因此,会调用复制构造函数。

唯一的例外是在返回语句中:

// 如果 arr 是局部变量,它将在此隐式移动
return arr;

要在您的情况下移动向量,您必须使用 std::move

vector<int> temp_a = move(arr);

然而,在这种情况下,整个函数也可以简化为:

void printArray(const vector<int>& arr)
{
    for(int x : arr)
        cout << x << '\n';
}
英文:

No, the move constructor of std::vector won't be used in that instance; the copy constructor will be used instead.

In general, moves don't happen implicitly, because every expression made of an identifier (unqualified-id) is an lvalue (e.g. arr is an lvalue). The move constructor accepts a std::vector&amp;&amp; rvalue reference, and that cannot bind to lvalues. As a result, the copy constructor is called.

The only exception to this rule is in a return statement:

// if arr is a local variable, it will be moved implicitly here
return arr;

To move the vector in your case, you must use std::move:

vector&lt;int&gt; temp_a = move(arr);

However, the whole function could also be simplified to:

void printArray(const vector&lt;int&gt;&amp; arr)
{
    for(int x : arr)
        cout &lt;&lt; x &lt;&lt; &#39;\n&#39;;
}

huangapple
  • 本文由 发表于 2023年8月10日 20:52:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定