EOS multi_index 删除动作 erase 时错误 The table operation is not allowed

yufei       5 年, 5 月 前       1439

在开发 EOS 合约过程中,有时候我们需要遍历一个 multi_index 表来删除 (erase) 一些不用的数据,通常情况下,我们会下面这样实现

unbox _tbl(_self,_self.value);

for( auto it = _tbl.begin(); it != _tbl.end(); it++) {
    _tbl.erase(it);
}

但这样是会报错的,错误信息如下

Exception Details: 3160005 table_operation_not_permitted: The table operation is not allowed
dereference of deleted object

究其原因,是因为删除动作发生时,迭代器就立刻失效了

正确的解决方案是

unbox _tbl(_self,_self.value);
auto ite = _tbl.begin();
while( ite != _tbl.end()) {
    ite = _tbl.erase(ite);
}

删除动作成功后, erase() 方法会返回下一个迭代数据

如果要根据条件来删除,不符合条件的则过滤,那么可以使用下面这种方法

unbox _tbl(_self,_self.value);
auto ite = _tbl.begin();
while( ite != _tbl.end()) {
    if (ite->status == 0 && ite->created_at < fivedays_ago) {
        ite = _tbl.erase(ite);
    } else {
        ite++;
    }
}
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.