when to use finalize in mongodb cxx r3.0.2 driver
To understand the difference between the two construct, we need to understand the difference between 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 which type is 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 if it is new to you.
finalize
returns a BSON document of type bsoncxx::document::value
from a temporary buffer. So finalize
returns an Owning BSON Document.
On the other hand, Non-owning BSON Documents are instance of bsoncxx::document::view
; a view into an Owning BSON Document. And as mentioned in the documentation,
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.
Also in the BSON Document lifetime explicitly mentioned with an example that
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.