4.2.3 节中的 C++ 复制省略之旅

Tour of C++ copy elision in Section 4.2.3

我正在阅读第 4.2.3 节初始化容器,C++ 第二版之旅

它说:

Vector read(istream& is)
{
     Vector v;
     for (double d; is>>d;)
         v.push_back(d);
     return v;
}

... The way to provide Vector with a move constructor, so that returning a potentially huge amount of data from read() is cheap, is explained in §5.2.2:

Vector v = read(cin);  // no copy of Vector elements here

是否保证上述表达式将被复制省略(在 C++17 中)? 我认为 return 中的 v 是一个左值和局部变量,因此它 可以 被复制省略但不保证被省略。 我在这里遗漏了什么吗?

Is it guaranteed that the above expression will be copy-elided (in C++17)?

I think v in the return is an lvalue & a local variable, so it can be copy-elided but is not guaranteed to be elided. Am I missing something here?

来自copy_elision

Non-mandatory elision of copy/move (since C++11) operations

In a return statement, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring cv-qualification) as the function return type. This variant of copy elision is known as NRVO, "named return value optimization".

因此即使在 C++17 中也无法保证 NRVO。

但是,如果不应用,移动构造函数就会完成(有关详细信息,请参阅 return statement)。