Object Lifecycle

This page documents the order of creation and destruction for libmongoc’s main struct types.

Clients and pools

Call mongoc_init() once, before calling any other libmongoc functions, and call mongoc_cleanup() once before your program exits.

A program that uses libmongoc from multiple threads should create a mongoc_client_pool_t with mongoc_client_pool_new(). Each thread acquires a mongoc_client_t from the pool with mongoc_client_pool_pop() and returns it with mongoc_client_pool_push() when the thread is finished using it. To destroy the pool, first return all clients, then call mongoc_client_pool_destroy().

If your program uses libmongoc from only one thread, create a mongoc_client_t directly with mongoc_client_new() or mongoc_client_new_from_uri(). Destroy it with mongoc_client_destroy().

GridFS objects

You can create a mongoc_gridfs_t from a mongoc_client_t, create a mongoc_gridfs_file_t or mongoc_gridfs_file_list_t from a mongoc_gridfs_t, create a mongoc_gridfs_file_t from a mongoc_gridfs_file_list_t, and create a mongoc_stream_t from a mongoc_gridfs_file_t.

Each of these objects depends on the object it was created from. Always destroy GridFS objects in the reverse of the order they were created. The sole exception is that a mongoc_gridfs_file_t need not be destroyed before the mongoc_gridfs_file_list_t it was created from.