gpt4 book ai didi

c++ - auto && outside range-for

转载 作者:行者123 更新时间:2023-11-30 03:56:29 24 4
gpt4 key购买 nike

我假设这样写对吗

auto && x = ...;

在 for 范围的 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(); 属于第二个上下文,并且没有任何异常(exception)情况适用。因此,临时文件在引用的生命周期内持续存在。所以这段代码没有任何问题。

关于c++ - auto && outside range-for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28475630/

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