簡體   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