Search code examples
c++c++11mongo-cxx-driver

mongocxx cursor and rvalue references


I was looking to the mongocxx query exemples and I don't get whats the point of using auto&& over auto& here.

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

In the documentation, they use it this way:

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

I want to use for(auto& doc : cursor)

What is the best practice here, and why ?


Solution

  • In this bit:

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

    The "range expression" in "range for" can return a temporary.

    It is a "best practice" to use rvalue reference here (when using auto).

    Have a look at this: http://en.cppreference.com/w/cpp/language/range-for

    Quote:

    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.

    And this:

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

    Quote:

    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.