When to use finalization in mongodb cxx r3.0.2 driver

I'm confused, in the online doc code snippets , it shows the use of finalization when calling the update_many method, for example:

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); 

But I saw the example code in the mongocxx driver code without finalizing

  // 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 } 

So what is the difference between using finalization or not using? How to make a choice?

+5
source share
1 answer

To understand the difference between the two constructs, we need to understand the difference between Ownership of BSON documents (values) and Non-Owners of BSON documents (views) by diving into the source code and Working with BSON documents in the documentation .

Ownership of BSON documents of type bsoncxx::document::value represents those documents that own their data buffer, so when the value is out of scope, its buffer is freed. Here you can find out about here or even better here if this is new to you.

finalize returns a BSON document of type bsoncxx::document::value from a temporary buffer. Therefore finalize returns a BSON Native document.

Non-BSON documents, on the other hand, are an instance of bsoncxx::document::view ; view of BSON's own document. And, as stated in the documentation,

In performance-critical code, passing views around is preferable to using values, because we can avoid redundant copying. In addition, the transmission of the presentation of the document allows us to use the document several times.

Also in the lifetime of a BSON document, it is explicitly mentioned with an example that

It is essential that document::values survive any document::views that used them. If the base value is cleared, the view will be left with a dangling pointer.

+1
source

Source: https://habr.com/ru/post/1259779/


All Articles