c++ - 生命周期延长和条件运算符

标签 c++ c++11 rvalue-reference object-lifetime temporary-objects

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

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

当初始化器不是一个简单的表达式,而是使用条件运算符时,这是否也有效?

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

如果其中一个结果是临时对象,而另一个不是,该怎么办?

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

当条件为假时,C++ 是否要求延长临时对象的生命周期?

在回答 this question 时出现问题关于不可复制的对象。

最佳答案

这两个都很好。

§5.16 说(特别删节):

2 If either the second or the third operand has type void

没有。

3 Otherwise, if the second and third operand have different types

没有。

4 If the second and third operands are glvalues of the same value category

不。 (在第一个中,两个都是纯右值,在第二个中是一个左值,一个是纯右值。)

5 Otherwise, the result is a prvalue

好的,所以这两个结果都是纯右值。所以绑定(bind)没问题,但是绑定(bind)到什么?

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 (continued) After those conversions, one of the following shall hold:

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)

无论如何,条件表达式的结果是一个新的临时纯右值,它是通过绑定(bind)到您的引用而扩展的值。

关于c++ - 生命周期延长和条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14405837/

相关文章:

c++ - 3d vector - 变换和减去

c++ - 如何在C++中高效实现无穷大和负无穷大的支持算术?

c++ - 如何在文件中存储每 channel 16 位的图像?

c++ - 从 Lambda 中调用虚拟父保护函数

c++ - QMetaEnum 和强类型枚举

c++ - virtual destructor=default 和空体有什么区别吗?

C++11 STL 容器和线程安全

c++ - 来自右值的非常量类型引用

c++ - C++如何对右值引用进行模板推导?

c++ - 获取要使用的 move 构造函数/赋值运算符