简体   繁体   English

是否在?:expression中创建的C ++临时对象的生命周期是通过将其绑定到本地const引用来扩展的?

[英]Is the lifetime of a C++ temporary object created in ?: expression extended by binding it to a local const reference?

It is not clear to me whether the lifetime of a temporary object would be extended by binding it to a const reference in a ?: expression: 我不清楚临时对象的生命周期是通过将它绑定到?:表达式中的const引用来扩展的:

class Foo {...};

Foo *someLValue = ...;

const Foo& = someLValue ? *someLValue : Foo();

Is the lifetime of the temporary created by calling the default constructor Foo() extended by binding it to the local const ref even though the binding is conditional? 通过将默认构造函数Foo()通过绑定到本地const ref来扩展创建临时文件的生命周期,即使绑定是有条件的吗? Or does this create a dangling reference because the temporary value of Foo() would be destroyed at the end of the ?: expression? 或者这会创建一个悬空引用,因为Foo()的临时值将在?:表达式的末尾被销毁?

In this code, the second and third operand of the conditional operator have different value categories (lvalue and prvalue). 在此代码中,条件运算符的第二个和第三个操作数具有不同的值类别(左值和右值)。

That means that the result of the conditional operator is a prvalue of type Foo , which denotes a temporary object copy-initialized from the selected operand. 这意味着条件运算符的结果是Foo类型的prvalue,它表示从所选操作数复制初始化的临时对象。

The reference binds directly to this temporary object and so the temporary's lifetime is extended. 引用直接绑定到此临时对象,因此临时生命周期延长。

Notes: 笔记:

  • The reference never binds directly to *someLValue , nor even to Foo() . 引用永远不会直接绑定到*someLValue ,甚至也不会绑定到Foo()
  • The temporary being initialized from Foo() is a copy elision context so you may not be able to observe the temporary in this case. Foo()初始化的临时值是一个复制省略上下文,因此在这种情况下您可能无法观察到临时值。
  • The temporary is non- const even though the reference is to const . 临时是非const即使引用是const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM