c++ - mongocxx 游标和右值引用

标签 c++ c++11 mongo-cxx-driver

我正在寻找 the mongocxx query exemples我不明白在这里使用 auto&& 而不是 auto& 有什么意义。

auto cursor = db["restaurants"].find({}, opts);
        for (auto&& doc : cursor) {
            std::cout << bsoncxx::to_json(doc) << std::endl;
}

documentation ,他们这样使用它:

mongocxx::cursor cursor = collection.find(document{} << finalize);
for(auto doc : cursor) {
  std::cout << bsoncxx::to_json(doc) << "\n";
}

我想使用 for(auto& doc : cursor)

这里的最佳实践是什么,为什么?

最佳答案

在这一点上:

for (auto&& doc : cursor)
...

“range for” 中的“range expression” 可以返回 temporary .

在此处使用右值引用是“最佳实践”(使用auto 时)。

看看这个: http://en.cppreference.com/w/cpp/language/range-for

引用:

If range_expression returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the rvalue reference __range, but beware that the lifetime of any temporary within range_expression is not extended.

还有这个:

http://www.artima.com/cppsource/rvalue.html

引用:

An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non const) lvalue reference to an rvalue.

关于c++ - mongocxx 游标和右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40376268/

相关文章:

c++ - mongocxx 如何从 View 中构建文档?

c++ - 将包含数组的 BSON 文档转换为 JSON,从转换后的 JSON (C++) 中删除数组

c++ - 为什么无法从我的光照着色器访问 G-Buffer?

java - Java Socket 客户端和 C++(基于 Boost)服务器之间的联网

c++ - "Conversion"从类型到相同类型导致错误

c++ - 无法针对 Fedora 中的 mongo C++ 驱动程序进行编译

c++ - 如何乘以大于 uint64 的整数?

c++ - 将字段的偏移量作为模板参数传递给该字段

postgresql - 如何在 postgres 数据库中对模式下的表执行选择?

c++ - 为什么这个 C++11 lambda 的行为不像我预期的那样?