第一次在这里发帖,这是我第一次需要自己问一个问题:我已经搜索了答案,但找不到。
我在 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_t
、type_t
、operator_t
是枚举类型(在类LogicFormula中用enum声明),大写字符的东西是只是这些类型的常量(在程序的其余部分工作正常)和 ListOfConstants
是另一个类,但我认为这不重要,实际上在这个测试中 vector original.children 是空的并且 original.list_of_constraints
为 NULL...
而且这个错误是一个运行时错误,它编译得很好......
最佳答案
我执行了您的代码(不包括一些变量,如 id
、type_formula
),没有任何问题。您确定 main
中的代码是您所有的代码吗?
问题可能出在这一行:
a = testLogic();
注意是assignment
不是copy
。因此该语句将使用编译器为类 LogicFormula
生成的 operator=
而不是使用 copy constructor
。默认的 operator=
将按位复制 list_of_constants
和 children
而不是循环遍历容器。 testLogic
中的 f
将被销毁,list_of_constants
和 children
也将被销毁。所以在赋值后 a
将有无效的成员。
另一个问题可能是您没有在构造函数中初始化 children
。 testLogic
的返回值将使用 copy constructor
进行复制,在其中它将尝试访问 children
。
关于C++ Vector 迭代器不兼容,但迭代器似乎对我有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483422/