enable_shared_from_this使用

2020-11-04  本文已影响0人  zlcook
class FileBasedWal final : public Wal
                         , public enable_shared_from_this<FileBasedWal> {

~FileBasedWal() {
    // FileBasedWal inherits from std::enable_shared_from_this, so at this
    // moment, there should have no other thread holding this WAL object
    // Close the last file
    closeCurrFile();
    LOG(INFO) << idStr_ << "~FileBasedWal, dir = " << dir_;
}

// FileBasedWal 对象直到上面的所有FileBasedWalIterator都释放后,其才会调用析构函数,
// 如果继承enable_shared_from_this,你在一个类方法中无法完成这一步: 返回一个FileBasedWalIterator,该FileBasedWalIterator的参数为FileBasedWal 的shared_ptr智能指针
std::unique_ptr<LogIterator> iterator(LogID firstLogId,
                                                         LogID lastLogId) {
    return std::make_unique<FileBasedWalIterator>(shared_from_this(), firstLogId, lastLogId);
}
};


class FileBasedWalIterator final : public LogIterator {
public:
    // The range is [startId, lastId]
    // if the lastId < 0, the wal_->lastId_ will be used
    FileBasedWalIterator(std::shared_ptr<FileBasedWal> wal,
                         LogID startId,
                         LogID lastId = -1);
;
    virtual ~FileBasedWalIterator();

    LogIterator& operator++() override;

    bool valid() const override;

    LogID logId() const override;

private:
    // Holds the Wal object, so that it will not be destroyed before the iterator
    std::shared_ptr<FileBasedWal> wal_;
};



int main() {
      std::unique_ptr<FileBasedWalIterator> iter1;
      std::unique_ptr<FileBasedWalIterator> iter2;
    {
         std::shared_ptr<FileBasedWal> wal(new FileBasedWal(....));
         iter1 = wal->iterator(...);
         iter2 = wal->iterator(...);
         // 作用域推出后,wal并不会被析构,因为iter对其进行了引用
    }
    iter其它操作
    iter1,iter2都析构后,wal才会析构
}
上一篇下一篇

猜你喜欢

热点阅读