2016-10-19 45 views
1

我正在使用mongocxx驱动程序,并且正在尝试对集合执行基本插入操作。Mongodb C++在插入到对象中的集合时崩溃

如果我只是遵循指导here,它工作正常。

但是,如果我将db和集合实例放入对象中,则插入在运行时崩溃。所以,一个简单的例子,我有一个数据库,收集情况下一个结构,并尝试通过这些实例做插入主创造的东西的一个实例()后:

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

我明白,这能通过启动主数据库和集合并仅存储Thing内的集合的指针来解决。 然而,我不知道崩溃的原因,以及是否可以将db集合实例放入对象中。

回答

2

我想问题可能是在open_connection栈上创建mongocxx::instance inst{};,所以在open_connection年底inst被破坏,一些数据可能是不确定的。

documentation

生命周期:司机的唯一实例必须围绕保持。

移动inst为主要功能。