C++11 是否保证 return 语句中的局部变量将被移动而不是复制?

Does C++11 guarantee the local variable in a return statement will be moved rather than copied?

本文关键字:移动 复制 局部变量 是否 return 语句 C++11      更新时间:2023-10-16
#include <vector>
using namespace std;
struct A
{
A(const vector<int>&) {}
A(vector<int>&&) {}
};
A f()
{
vector<int> coll;
return A{ coll }; // Which constructor of A will be called as per C++11?
}
int main()
{
f();
}

collreturn A{ coll };xvalue吗?

C++11 是否保证A(vector<int>&&)f回归时会被调用?

C++11 不允许从中移动coll。它只允许在return语句中隐式移动,当你执行return <identifier>时,其中<identifier>是局部变量的名称。任何比这更复杂的表达式都不会隐式移动。

而比这更复杂的表达式不会经历任何形式的省略。