繁体   English   中英

C ++ Vector迭代器不兼容,但迭代器似乎对我有效

[英]C++ Vector iterators incompatible, but iterators seem to be valid to me

在这里发帖,这是我第一次自己提出问题:我已经找到了答案,但我找不到答案。

我在调试模式下使用Visual Studio 2013得到错误“ Expression: vector iterators incompatible ”。这个错误的通常原因是在for中,迭代器不指向同一个对象,或者结束迭代器因为a而无效在循环中重新分配,但在这里我没有看到类似的东西......

我的LogicFormula类的复制构造函数中发生错误:

struct LogicFormula {
  id_t ID;
  type_t type_formula;
  operator_t type_operator;
  bool bool_value;
  std::string name;
  ListOfConstants *list_of_constants;
  std::vector<LogicFormula*> children;

  LogicFormula(const LogicFormula &original) {
    type_formula = original.type_formula;
    type_operator = original.type_operator;
    bool_value = original.bool_value;
    name = original.name;
    for (std::vector<LogicFormula*>::const_iterator it =
      original.children.cbegin(); it != original.children.cend(); ++it)
      children.push_back(new LogicFormula(**it));
    if (original.list_of_constants)
      list_of_constants = new ListOfConstants(*(original.list_of_constants));
    else
      list_of_constants = NULL;
  }

  LogicFormula(bool value) {
    type_formula = PROPOSITIONAL_CONSTANT;
    type_operator = LEAF;
    bool_value = value;
    list_of_constants = NULL;
  }

  // [...]
};

在该行检测到错误:

for (std::vector<LogicFormula*>::const_iterator it =
  original.children.cbegin(); it != original.children.cend(); ++it)

我做了一个引发错误的最小主函数:

int main ( int argc, char* argv[] ) {

    LogicFormula a(true);
    a = testLogic();
    return 0;
}

我希望我能给你一切,如果我的英语不好,我很抱歉:我是法国人。

编辑:对不起,我忘了给功能testLogic:

LogicFormula testLogic(void) {
    LogicFormula f(true);
    return f;
}

然后通过return f;对复制构造函数进行调用return f;

仅供参考, id_ttype_toperator_t是枚举类型(在LogicFormula类中用枚举声明),大写字符事物只是这些类型的常量(在程序的其余部分工作正常)而ListOfConstants是另一个类,但我不要认为这很重要,实际上在这个测试中,矢量original.children是空的并且original.list_of_constraints是NULL ...并且错误是运行时错误,它编译得很好......

我执行你的代码(不包括一些变量,如idtype_formula )没有任何问题。 你确定main的代码是你所拥有的吗?

问题可能出在这一行:

 a = testLogic();

请注意,它是assignment而不是copy 因此语句将使用编译器生成的operator= for class LogicFormula而不是使用copy constructor 默认的operator=将逐位复制list_of_constantschildren而不是循环访问容器。 testLogicf将被销毁, list_of_constantschildren也将被销毁。 因此,分配后a将有无效的成员。

另一个问题可能是您没有在构造函数中初始化children 将使用copy constructor复制testLogic的返回值,在该copy constructor中,它将尝试访问children

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM