gpt4 book ai didi

c++ - 将从函数返回 vector> 调用 C++11 中的任何 move 构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:59 24 4
gpt4 key购买 nike

在 C++11 中将返回一个 vector<vector<int> >从函数调用任何 move 构造函数?还是下面的代码只是制作所有 vector 及其元素的另一个拷贝?

vector< vector<int> > Func() {
vector< vector<int> > vec;
//vec is filled here
return vec;
}

对于简单类型的 STL 容器,当使用 move 构造函数或将它们作为函数值返回时进行复制时,是否有一个通用的发现?

最佳答案

return 语句在标准中特别涵盖,可自动视为 move 。所以是的,这将调用 move 构造函数。

这方面的法律条文是 C++11,[class.copy]§31+32:

31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object ... This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function's return value
  • ...

32 When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue....

(强调我的)

结合并应用于您的情况,这意味着当从函数返回局部变量时,首先尝试 move ,只有在不可能的情况下,才会执行复制。

(而且,正如@BjornPollex 指出的那样,很可能连此举都将被省略)

关于c++ - 将从函数返回 vector<vector <int>> 调用 C++11 中的任何 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com