[英]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_t
, type_t
, operator_t
是枚舉類型(在LogicFormula類中用枚舉聲明),大寫字符事物只是這些類型的常量(在程序的其余部分工作正常)而ListOfConstants
是另一個類,但我不要認為這很重要,實際上在這個測試中,矢量original.children是空的並且original.list_of_constraints
是NULL ...並且錯誤是運行時錯誤,它編譯得很好......
我執行你的代碼(不包括一些變量,如id
, type_formula
)沒有任何問題。 你確定main
的代碼是你所擁有的嗎?
問題可能出在這一行:
a = testLogic();
請注意,它是assignment
而不是copy
。 因此語句將使用編譯器生成的operator=
for class LogicFormula
而不是使用copy constructor
。 默認的operator=
將逐位復制list_of_constants
和children
而不是循環訪問容器。 testLogic
的f
將被銷毀, list_of_constants
和children
也將被銷毀。 因此,分配后a
將有無效的成員。
另一個問題可能是您沒有在構造函數中初始化children
。 將使用copy constructor
復制testLogic
的返回值,在該copy constructor
中,它將嘗試訪問children
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.