我有课
class Person {
// some other fields for this object
std::vector<string> relatives;
}
然后是一个返回 Person 列表的 util 函数
std::vector<Person> getSomePerson() {
// implementation details...
}
现在我想遍历:
for (auto&& p: getSomePerson()) { <---- do I need the rvalue reference???
// use p
some_other_vector.insert(
std::make_move_iterator(p.relatives.begin()),
std::make_move_iterator(p.relatives.end())
)
}
问题:我需要右值引用吗?它与在此处使用简单引用有什么不同吗?
最佳答案
在你的情况下:
for (auto&& p: getSomePerson()) {
for (auto& p: getSomePerson()) {
这两行完全相同。
auto&&
这里是转发引用。它将根据初始化的内容推断为右值或左值引用。
正在迭代的范围是 vector 类型的右值。它的迭代器的 operator*
返回一个左值引用。
因此 p
将是对 Person
的左值引用。
auto&&
可以在这里(以及许多其他地方)解释为“我不关心我绑定(bind)到什么,但不要制作任何额外的拷贝”。这是 for(:)
循环的合理默认值。
如果您的范围返回值,auto&&
将成为一个右值引用,并且将发生引用生命周期延长。 auto&
将无法编译。
auto const&
是另一个合理的选择;它很像 auto&&
,但您也保证不会修改您所指的内容。
关于c++ - 右值引用用法 : needed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56347712/