何时在 mongodb cxx r3.0.2 驱动程序中使用 finalize

when to use finalize in mongodb cxx r3.0.2 driver

我很困惑,在 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和不使用finalize有什么区别呢?如何做出选择?

要了解这两个构造之间的区别,我们需要了解 Owning BSON Documents (values) and Non-owning BSON Documents (views) by diving into the source code and the Working with BSON document page in the documentation.

之间的区别

Owning BSON Documents如果你是新手bsoncxx::document::value represent those documents that own their buffer of data so when the value goes out of scope, his buffer is freed. You can learn about scope here or even better here

finalize returns 来自临时缓冲区的 bsoncxx::document::value 类型的 BSON 文档。所以 finalize returns 一个 拥有 BSON 文档.

另一方面,非拥有 BSON 文档bsoncxx::document::view 的实例; 拥有 BSON 文档 的视图。正如文档中所述,

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 any document::views that use them. If the underlying value gets cleaned up, the view will be left with a dangling pointer.