代码之家  ›  专栏  ›  技术社区  ›  Eyelash

移动复制和/或分配mongodb cxx光标

  •  2
  • Eyelash  · 技术社区  · 7 年前

    我不需要Mongo的完整功能集,基本上只需要CRUD:创建、读取、更新、删除和查找,可能需要传递一些更高级的参数(读/写关注点等)。

    我想围绕mongocxx::cursor创建一个包装类,以便find()的结果可以“稍后”以存储API使用的数据格式进行迭代。“稍后”是指(包装的)游标返回到一个抽象类,该抽象类可以迭代结果并根据模式验证数据,或者可以跳过条目,或者可以将结果分组(异步)发送到最终客户机,等等。

    例如,如果我有:(这个例子略为缩写)

    using namespace mongocxx;
    
    class QMongoClient
    {
        static instance _instance;
    
        QMongoClient(QString url) : _client( uri( qPrintable(url) ) );  
        client _client;
        QMongoDatabase operator[](QString d);
    };
    
    class QMongoDatabase
    {
        QMongoDatabase(database db) : _database(db);
        database _database;
        QMongoCollection operator [](QString c);
    };
    
    class QMongoCollection
    {
        QMongoCollection(collection c) : _collection(c);
        collection _collection;
        //create... same as insert()
        //read... same as find_one()
        //update... same as upsert() or update()
        //delete...
        //find... a query will be provided
        QMongoCursor findAll() { cursor c = _collection.find({}); return QMongoCursor(c); };
    };
    
    class QMongoCursor
    {
        QMongoCursor(cursor c) : _cursor(c);
        //copy/move/assign constructors needed, probably
    
        cursor _cursor;
    
        QString data(); //return document contents as JSON string, for instance
    
        //begin() <-- iterator
        //end() <-- iterator
    };
    

    error: call to implicitly-deleted copy constructor of 'mongocxx::v_noabi::cursor'
    

    这样做的目的是:

    QMongoClient client("mongodb://url...");
    QMongoDatabase db = client["somedbname"];
    QMongoCollection coll = db["somecollection"];
    QMongoCursor c = coll.findAll();
    
    //or more abbreviated:
    QMongoCursor c = client["somedbname"]["somecollection"].findAll();
    
    //iterate over c here as needed, or send it to another abstraction layer...
    

    例如,当QMongoCursor::findAll()完成时,返回的游标将被销毁,并且无法在QMongoCursor构造函数中复制。

    所以问题是:

    • 如果光标在超出范围且没有复制/移动构造函数时被销毁,我如何使其保持活动状态
    • 或者,我如何创建一个指向光标的指针,并知道它的寿命以及何时删除它

    我想我缺少一些c++语法或机制,比如移动赋值之类的。

    有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   acm    7 年前

    mongocxx::cursor 可移动,但您没有要求移动,您要求的是副本。尝试:

    QMongoCursor(cursor c) : _cursor(std::move(c));
    

    你也应该考虑的一件事是,如果你正在构建一个更高级别的工具包,你需要密切关注与之相关的生命周期规则 client , database collection cursor shared_ptr 与抽象类似,确保类型系统强制执行适当的生存期对您的usec案例是有利的。

    我们没有让司机那样工作,因为我们不想把这个决定强加给人们。相反,我们认为它可以而且应该被委托到更高级别的抽象,很可能与您正在构建的抽象非常相似。