c++ - 临时右值引用对象的生命周期

标签 c++ c++14 language-lawyer

假设您有这段代码(在 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/

相关文章:

c - 枚举常量声明与定义 - C 标准

c++ - 从带有 OpenGL 的 C++ 转换为 Objective-C 代码

c++ - 获取未初始化对象成员的地址是否定义明确?

c++ - vector.push_back() 崩溃

c++ - std::tuple 元素的延迟初始化

c++ - DLL 导出导致唯一指针问题

C++ 编译器允许循环定义?

c++ - 为什么 delete 运算符可以用在 const 上下文中?

c++ - std::vector push_back 上的段错误/"Vector is not dereferencable"

c++ - 在迭代 DFS 与递归 DFS 中维护当前节点的上下文