假设您有这段代码(在 c++14 中):
auto && a = a_function_returning_a_temp_rvalue();
返回值存储在哪里,何时调用其析构函数,是a
const
(考虑到函数不返回const
), 标准中是如何规定的?
(这是否合法)
此外,您是否确认临时对象确实绑定(bind)到 a
,并且不会调用 operator=
这两个构造函数?
它在 g++ 上编译并避免键入长模板类,但在使用它之前,我想检查它是否在 c++14 中明确说明
最佳答案
规则在[class.temporary]中:
There are three contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...] The third context is when a reference is bound to a temporary.116 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) [...]
— The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is [...]
— A temporary bound to a reference in a new-initializer (5.3.4) persists until [...]
在这个例子中:
auto && a = a_function_returning_a_temp_rvalue();
我假设该函数返回类型为 T
的内容(与 T&
或 T&&
相对)。在这种情况下,我们确实有一个临时绑定(bind)到一个引用,并且这些异常(exception)都不适用。因此,该临时对象的生命周期延长了 a
的生命周期。
关于c++ - 临时右值引用对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43354360/