生命期扩展和条件运算符 [英] Lifetime extension and the conditional operator

查看:145
本文介绍了生命期扩展和条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

local lvalue references-to-const和rvalue references可以延长临时表的生命周期:

local lvalue references-to-const and rvalue references can extend the lifetime of temporaries:

const std::string& a = std::string("hello");
std::string&& b = std::string("world");

当初始化不是一个简单的表达式但是使用条件运算符时, p>

Does that also work when the initializer is not a simple expression, but uses the conditional operator?

std::string&& c = condition ? std::string("hello") : std::string("world");

如果结果之一是临时对象,而另一个结果不是? p>

What if one of the results is a temporary object, but the other one isn't?

std::string d = "hello";
const std::string& e = condition ? d : std::string("world");

当条件为假时,C ++是否允许扩展临时的生命周期?

Does C++ mandate the lifetime of the temporary be extended when the condition is false?

问题出现在回答有关不可复制对象的此问题时。

The question came up while answering this question about non-copyable objects.

§5.16表示(非常简洁的)。

解决方案


推荐答案

):


2如果第二个或第三个操作数具有类型void

Nope.

不适用。


3否则,如果第二个和第三个操作数有不同类型

Nope.

不适用。


4如果第二个和第三个操作数相同值类别的glvalues

Nope. (In the first, both are prvalues and in the second one is a glvalue and one is a prvalue.)

不适用。 (第一个,两个都是prvalues,第二个是glvalue,一个是prvalue。)

5 Otherwise, the result is a prvalue


5否则结果是一个prvalue

Okay, so both of these result in prvalues. So the binding is fine, but what's the binding to?

好的,所以这两个结果都是prvalues。所以绑定很好,但绑定到什么?

6 Lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are per- formed on the second and third operands.


6 Lvalue-to-rvalue(4.1),array-to-pointer

Okay, so both are now rvalues if they weren't already.

好的,第二个和第三个操作数都要执行函数到指针

6 (continued) After those conversions, one of the following shall hold:


6(续)在这些转换之后,下列其中一项应该成立: / p>

第二个和第三个操作数具有相同的类型;结果是那种类型。如果操作数具有类类型,则结果是结果类型的临时临时值,根据第一个操作数的值,从第二个操作数或第三个操作数进行复制初始化。

The second and third operands have the same type; the result is of that type. If the operands have class type, the result is a prvalue temporary of the result type, which is copy-initialized from either the second operand or the third operand depending on the value of the first operand.

好的, std :: string(first_operand) std :: string (second_operand)

无论如何,条件表达式的结果是一个新的prvalue临时值,它是通过绑定到参考。

Regardless, the result of the conditional expression is a new prvalue temporary, and it's that value that's extended by binding to your references.

这篇关于生命期扩展和条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆