1

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

如果我只是按照此处介绍的指南进行操作,它就可以正常工作。

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

#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;
}

我意识到这可以通过在 main 中启动数据库和集合并在 Thing 中仅存储指向集合的指针来解决。但是,我想知道崩溃的原因,以及是否可以将 db 集合实例放在对象中。

4

1 回答 1

2

我认为问题可能是mongocxx::instance inst{};在堆栈中创建的open_connection,所以在结束时open_connectioninst销毁并且某些数据可能变得未定义。

文档

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

转到inst主要功能。

于 2016-10-19T11:53:53.730 回答