MongoDB C++ Driver mongocxx-4.0.0
Loading...
Searching...
No Matches
Instance

How to use a MongoDB C++ Driver instance.

Initialize the C++ Driver

Basic Usage

void example() {
// Do not use mongocxx library interfaces at this point!
{
// Initialize the MongoDB C++ Driver by constructing the instance object.
EXPECT(&mongocxx::instance::current() == &instance);
// Use mongocxx library interfaces at this point.
// Cleanup the MongoDB C++ Driver by destroying the instance object.
}
// Do not use mongocxx library interfaces at this point!
}

With Static Lifetime

Warning
This pattern depends on an exit-time destructor with indeterminate order relative to other objects with static lifetime being destroyed.
void example() {
// Do not use mongocxx library interfaces at this point!
{
// Initialize the MongoDB C++ Driver.
auto& instance = mongocxx::instance::current();
EXPECT(&mongocxx::instance::current() == &instance);
// Use mongocxx library interfaces at this point.
}
// Use mongocxx library interfaces at this point.
}
// Cleanup the MongoDB C++ Driver after returning from `main()` with indeterminate order relative to
// other objects with static lifetime being destroyed.

Errors

Instance Recreation

void example() {
{
EXPECT(&mongocxx::instance::current() == &instance);
try {
mongocxx::instance another_instance; // Throws.
EXPECT(false && "should not reach this point");
} catch (const mongocxx::exception& ex) {
EXPECT(ex.code() == mongocxx::error_code::k_cannot_recreate_instance);
}
EXPECT(&mongocxx::instance::current() == &instance);
}
}

Destroyed Instance

void example() {
{ mongocxx::instance instance; } // Initialize and cleanup.
try {
mongocxx::instance instance; // Throws.
EXPECT(false && "should not reach this point");
} catch (const mongocxx::exception& ex) {
EXPECT(ex.code() == mongocxx::error_code::k_cannot_recreate_instance);
}
try {
auto& instance = mongocxx::instance::current(); // Throws.
EXPECT(false && "should not reach this point");
} catch (const mongocxx::exception& ex) {
EXPECT(ex.code() == mongocxx::error_code::k_instance_destroyed);
}
}