[英]Why do I get the error 'vector iterators incompatible'?
我正在为我的程序编写一个小UI。 我有方法onMouseMotion()
,我可以用两种方式之一调用它(参见代码); 如果我通过std::function
调用它,则for循环停止条件中的!=
运算符会导致运行时异常vector iterators incompatible
。 为什么?
class Widget : public EventHandler
{
protected:
/* ... */
std::vector<Widget *> children_;
std::function<bool(Event &)> func_;
private:
bool onMouseMotion(Event &event);
/* ... */
};
Widget::Widget()
{
/* ... */
func_ = std::bind(&Widget::onMouseMotion, this, std::placeholders::_1);
/* ... */
}
bool Widget::processEvent(Event &event)
{
if (event.getType() == ui::EventType::MouseMotionEvent) {
/* Method 1 - onMouseMotion works ok */
onMouseMotion(event);
/* Method 2 - onMouseMotion throws */
//func_(event);
return true;
}
}
bool Widget::onMouseMotion(Event &event)
{
/* exception occurs on the next line, only when using Method 2 above */
for (auto child = children_.rbegin(); child != children_.rend(); ++child) {}
}
更新 :
for
循环时抛出异常,发生零迭代。 for
循环。 std::function
问题。 所以很明显
auto
定义了子的迭代器类型,由编译器静态确定(它不能在调用之间改变)。 child
类型是与rbegin()
和rend()
兼容的赋值 child
类型是与rbegin()
兼容的关系运算符,但在通过bind()
包装器调用时则不然 child
类型不能改变,因此在第二种情况下, rend()
的类型必须具有。 我看到以下可能性。
this
不同于在结合捕获(基类VS派生类,例如)在第一种情况下可能是不同 this
可以经由一个包装,从而改变它的类型的行为被递送。 总的来说,这很可能是一个MSVC错误。 提供的代码不编译,我不愿意尝试修改,可能无法重现该错误。 如果你可以发布一个编译的repro案例,我很乐意进一步调查并更新答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.