mongocxx 游标和右值引用
mongocxx cursor and rvalue references
我一直在寻找 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 expression"中的"range for"可以return一个temporary。
这里使用右值引用是"best practice"(使用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.
我一直在寻找 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 expression"中的"range for"可以return一个temporary。
这里使用右值引用是"best practice"(使用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.