auto && outside range-for

auto && outside range-for

我假设写作是正确的吗

auto && x = ...;

在范围的 for (...) 部分之外几乎没有任何意义,因为如果右侧确实是一个右值,它通常会停止存在于分号处然后 x指的是已经被破坏的东西。

换句话说:

Widget f () { ... }
...
auto && x = f();
// do something with x

错了吗?

来自标准[class.temporary]:

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when a default constructor is called to initialize an element of an array.

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
— A temporary object bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
— The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
— A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer.

auto&& x = f(); 属于第二个上下文,并且 none 的例外情况适用。因此,临时文件在引用的生命周期内持续存在。所以这段代码没有任何问题。