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

标签 c++ object vector iterator

第一次在这里发帖,这是我第一次需要自己问一个问题:我已经搜索了答案,但找不到。

我在 Visual Studio 2013 的 Debug模式下收到错误“Expression: vector iterators incompatible”。此错误的常见原因是在 for 中,迭代器未指向同一对象,或者结束迭代器由于循环期间的重新分配而变得无效,但在这里我没有看到类似的东西......

错误发生在我的 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;

调用复制构造函数

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

最佳答案

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

问题可能出在这一行:

 a = testLogic();

注意是assignment 不是copy。因此该语句将使用编译器为类 LogicFormula 生成的 operator= 而不是使用 copy constructor。默认的 operator= 将按位复制 list_of_constantschildren 而不是循环遍历容器。 testLogic 中的 f 将被销毁,list_of_constantschildren 也将被销毁。所以在赋值后 a 将有无效的成员。

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

关于C++ Vector 迭代器不兼容,但迭代器似乎对我有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483422/

相关文章:

c++ - STL set_symmetric_difference 的时间复杂度

c++ - 是否可以使用 boost::bind 来有效地连接函数?

javascript:通过增加 objectKeys 值来更新对象

JavaScript 创建新对象

c# - 创建的对象能够访问创建它的对象的成员

C++关键部分不起作用

python - 来自 Python 中另一个实例的实例

c++ - 对象的 ctor 和 dtor 必须在同一个线程上吗?

r - 如何从向量或列表中消除 n 个连续值?

vector - 为什么 Julia 没有在函数中获取正确的数据?