c++ - 正在通过 const ref undefined 行为捕获新构造的对象

标签 c++ c++11 constants undefined-behavior

以下(人为的示例)可以吗还是未定义的行为:

// undefined behavior?
const auto& c = SomeClass{};

// use c in code later
const auto& v = c.GetSomeVariable();

最佳答案

很安全。 Const ref 延长了临时变量的生命周期。该范围将是 const ref 的范围。

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:

  • a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.
  • a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. (note: such initialization is ill-formed as of DR 1696).
  • a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.
  • a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference.
  • a temporary bound to a reference in a reference element of an aggregate initialized using direct-initialization syntax (parentheses) as opposed to list-initialization syntax (braces) exists until the end of the full expression containing the initializer. struct A { int&& r; }; A a1{7}; // OK, lifetime is extended A a2(7); // well-formed, but dangling reference

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.

@Konrad Rudolph指出(并参见上面的最后一段):

"If c.GetSomeVariable() returns a reference to a local object or a reference that it is itself extending some object’s lifetime, lifetime extension does not kick in"

关于c++ - 正在通过 const ref undefined 行为捕获新构造的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648684/

相关文章:

c++ - 无法使用包含在类模板中的位字段成员聚合初始化结构类型的变量

c++ - std::thread 到 std::async 会带来巨大的性能提升。怎么可能?

c - 如何将 const 数组或变量数组传递给 C 中的函数?

PHP、SPL预定义常量

c++ - s 拷贝构造函数

c++ - 来自 const std::vector<>&; 的自动对象或引用?

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 继承默认构造函数在 gcc 中失败,但在 clang 中有效,哪个有 bug?

linq-to-sql - 具有常量值和投影的 Union(或 Concat 等)

c++ - 使用 QWebview 会出现编译错误,但这并不是因为 .pro 文件中缺少 Qt += webkit