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/