【发布时间】:2013-01-02 13:42:57
【问题描述】:
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 关于不可复制对象时出现了这个问题。
【问题讨论】:
-
对于
d,混合变体不需要std::move吗? -
d不能绑定到右值引用,它不是右值。 -
使用 ?: 没问题。在混合情况下,复制 d。由于 ?: 的两边总是以相同的类型结束,编译器知道创建一个对象。
-
@SethCarnegie:
d是一个左值,但表达式(true?d:std::string())是一个右值,它引用存储在d中的值。左值将经过左值到右值的转换(即读取存储在变量中的值)
标签: c++ c++11 rvalue-reference object-lifetime temporary-objects