Mongodb c++;插入对象内部的集合时崩溃

Mongodb c++;插入对象内部的集合时崩溃,mongodb,mongo-cxx-driver,Mongodb,Mongo Cxx Driver,我正在使用mongocxx驱动程序,我正在尝试对集合进行基本插入 如果我只是按照上面的指导方针去做,效果会很好 但是,如果我将db和集合实例放在一个对象中,则插入在运行时崩溃。因此,举一个简单的例子,我有一个包含数据库和集合实例的struct,在main()中创建Thing的实例后,尝试通过这些实例进行插入: #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 结构物{ mongocxx::客户端; mongocxx::数据库数据库数据库; mongocxx::集合coll; 无效开

我正在使用mongocxx驱动程序,我正在尝试对集合进行基本插入

如果我只是按照上面的指导方针去做,效果会很好

但是,如果我将db和集合实例放在一个对象中,则插入在运行时崩溃。因此,举一个简单的例子,我有一个包含数据库和集合实例的struct,在main()中创建Thing的实例后,尝试通过这些实例进行插入:

#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
结构物{
mongocxx::客户端;
mongocxx::数据库数据库数据库;
mongocxx::集合coll;
无效开放连接(常量字符*主机、常量字符*数据库名称、常量字符*coll\u名称){
mongocxx::实例inst{};
mongocxx::uri(主机);
client=mongocxx::client::client(uri);
db=客户机[db_名称];
coll=db[coll_name];
}
};
int main()
{
事物;
打开连接(“mongodb://localhost:27017“,”测试“,”插入测试“);
auto builder=bsoncxx::builder::stream::document{};

bsoncxx::document::value doc\u value=builder我认为问题可能是
mongocxx::instance inst{};
open\u connection
中的堆栈上创建的,因此在
open\u connection
结束时,
inst
被销毁,一些数据可能变得未定义

发件人:

生命周期:必须保留驱动程序的唯一实例

inst
移动到主功能

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>


struct Thing {
   mongocxx::client client;
   mongocxx::database db;
   mongocxx::collection coll;

   void open_connection(const char* host, const char* db_name, const char* coll_name) {
      mongocxx::instance inst{};
      mongocxx::uri uri(host);

      client = mongocxx::client::client(uri);
      db = client[db_name];
      coll = db[coll_name];
   }
};


int main()
{
   Thing thing;
   thing.open_connection("mongodb://localhost:27017", "test", "insert_test");

   auto builder = bsoncxx::builder::stream::document{};
   bsoncxx::document::value doc_value = builder << "i" << 1 << bsoncxx::builder::stream::finalize;

   auto res = thing.coll.insert_one(doc_value.view()); //crashes

   return 0;
}