Creation & Destruction#
BSON data structures are managed using the bson_doc
(C) or bson::document
(C++) types. These types own an associated region of memory that contains the
BSON data.
Creating (C)#
Creation of a new bson_doc
is performed using bson_new()
. When you are done
with a document object, it should be destroyed with bson_delete()
:
#include <bson/doc.h>
void c_create() {
// Create a new document boject
bson_doc doc = bson_new();
// Do stuff
// Destroy the object
bson_delete(doc);
}
The bson_doc
object is small and safe to pass and return by value from
functions and APIs.
Creating (C++)#
C++ code can create a document object using bson::document
:
#include <bson/doc.h>
void cxx_create() {
// Will be destroyed automatically
bson::document doc{::mlib_default_allocator};
}
It will automatically destroy the object when it leaves scope. Copying a
bson::document
will create a distinct copy of the data.
A C bson_doc
can be converted to a C++ bson::document
by passing it as an
r-value to the bson::document
constructor.
A C++ bson::document
can be converted to a C bson_doc
in two ways:
bson::document::get()
will return an lvalue reference to the wrappedbson_doc
. This returned object should never be used with a[[transfer]]
parameter.bson::document::release()
will relinquish ownership of the heldbson_doc
and return it to the caller. Thebson::document
object will be made null and the returnedbson_doc
is now the responsibility of the caller.
Copying#
If you have an existing BSON object and want to duplicate it, bson_new()
can
also be used for that purpose:
const bson_doc* get_some_bson_doc(void);
void copy_a_document() {
bson_doc dup = bson_new(*get_some_bson_doc());
// ...
bson_delete(dup);
}
C++ code can simply copy the bson::document
object to get a distinct copy.
Reserving Memory#
When creating a BSON document, it may be useful to reserve additional memory for
the document data that we will later insert data into. This can be done by
passing an integer number of bytes when constructing the instance with
bson_new()
or bson::document
:
void reserve_space() {
bson_doc large = bson_new(1024);
// ...
bson_delete(large);
}
Note
Even though we allocate data for the document up-front, the returned object is still empty.