2016-10-19 81 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爲主要功能。