私は 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;
}
データベースとコレクションをメインで開始し、コレクションへのポインターのみを Thing 内に格納することで、これを解決できることがわかりました。ただし、クラッシュの理由と、db コレクション インスタンスをオブジェクト内に配置できるかどうかについて疑問に思っています。