gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:36:25 26 4
gpt4 key购买 nike

我正在寻找 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com