我很困惑,在 online doc, 的代码片段中它显示了调用 update_many 方法时 finalize 的用法,如下所示:
mongocxx::stdx::optional<mongocxx::result::update> result =
collection.update_many(
document{} << "i" << open_document <<
"$lt" << 100 << close_document << finalize,
document{} << "$inc" << open_document <<
"i" << 100 << close_document << finalize);
但是我在没有finalize的mongocxx驱动代码中看到了示例代码
// Update multiple documents.
{
// @begin: cpp-update-multiple-documents
bsoncxx::builder::stream::document filter_builder, update_builder;
filter_builder << "address.zipcode"
<< "10016"
<< "cuisine"
<< "Other";
update_builder << "$set" << open_document << "cuisine"
<< "Category To Be Determined" << close_document << "$currentDate"
<< open_document << "lastModified" << true << close_document;
db["restaurants"].update_many(filter_builder.view(), update_builder.view());
// @end: cpp-update-multiple-documents
}
那么使用 finalize 和不使用它有什么区别呢?如何做出选择?
最佳答案
要了解这两种构造之间的区别,我们需要了解Owning BSON Documents (values) 之间的区别。和 Non-owning BSON Documents (views)通过深入研究源代码和 Working with BSON document documentation 中的页面.
拥有 BSON 文档,类型为 bsoncxx::document::value
表示那些拥有其数据缓冲区的文档,因此当 value 超出范围时,他的缓冲区被释放。您可以了解scope here甚至better here如果它对你来说是新的。
finalize
从临时缓冲区返回 bsoncxx::document::value
类型的 BSON 文档。所以 finalize
返回一个 Owning BSON Document。
另一方面,非拥有 BSON 文档是 bsoncxx::document::view
的实例; 拥有 BSON 文档的 View 。如文档中所述,
In performance-critical code, passing views around is preferable to using values because we can avoid excess copying. Also, passing a view of a document allows us to use the document multiple times.
也在 BSON Document lifetime 中用一个例子明确提到
It is imperative that
document::values
outlive anydocument::views
that use them. If the underlying value gets cleaned up, the view will be left with a dangling pointer.
关于mongodb - 何时在 mongodb cxx r3.0.2 驱动程序中使用 finalize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40615872/