Search code examples
c++mongodbinstancemongo-cxx-driver

How to get the current instance of MongoDB with C++?


I generate an object of the class mongocxx::instance in a constructor.

constructor:

mongocxx::instance instance{};
mongocxx::client client
{
    mongocxx::uri{}
};
database= client["test"];

Now I need to get this instance in a function. I tried this:

function:

mongocxx::instance::current();
database.drop();

My program crashes at the line mongocxx::instance::current();.

Can someone help me?


Solution

  • Once your constructor ran to completion, the mongocxx::instance object that you had on the stack has been destroyed. You need to keep an instance of instance around that outlives the other types.

    Please see the instance management example in the sources for more examples of how to use this type.