右值引用用法:需要
rvalue reference usage: needed?
我有一个类
class Person {
// some other fields for this object
std::vector<string> relatives;
}
然后是一个 util 函数,它返回 Person 列表
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&&
这里是转发参考。 它将推断为右值或左值引用,具体取决于初始化的内容。
正在迭代的范围是向量类型的右值。 其迭代器的operator*
返回一个左值引用。
因此p
将是Person
的左值引用。
auto&&
在这里(以及许多其他地方(可以解释为"我不在乎我绑定什么,但不做任何额外的副本"。 这是for(:)
循环的合理默认值。
如果范围返回值,则auto&&
将成为右值引用,并且引用生存期将延长。 auto&
将无法编译。
auto const&
是另一个合理的选择;它很像auto&&
,但你也承诺不修改你所指的东西。
相关文章:
- std::原子加载和存储都需要吗
- 需要帮助设置在C++中使用的Potrace
- 是否需要删除包含对象的"pair"?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- C++我需要了解在哪里使用指针和双指针
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 这个指针在c++中的用法
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 我需要将多个函数组合为一个函数
- 概念中的cv限定符需要表达式参数列表
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 当C++中需要自动删除时,这是静态的正确用法吗?
- 代码中的"sprintf"用法是否需要释放内存?
- 右值引用用法:需要
- 需要有关初始化期间动态绑定习惯用法的帮助
- c++linux中的静态链接用法:每次更改库时,是否需要重新编译所有内容
- 网络编程基础知识,需要帮助了解addrinfo/sockaddr_instructs的用法等
- 需要一个Ypsilon用法示例