Dan*_*tor 7 c++ iterator vector visual-c++ std-function
我正在为我的程序编写一个小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) {}
}
Run Code Online (Sandbox Code Playgroud)
更新:
for循环时抛出异常,发生零迭代.for循环的相同异常.std::function问题.所以很明显
auto为 child 定义一个迭代器类型,由编译器静态确定(它不能在调用之间更改)。child兼容rbegin()rend()child兼容关系运算符,但在通过包装器rbegin()调用时不兼容bind()child的类型必须改变。rend()我看到以下可能性。
this可能与绑定中捕获的值不同(例如,基类与派生类)this可以通过包装器传递,这会改变其类型行为。总的来说,这很可能是 MSVC 错误。提供的代码无法编译,我不愿意尝试修改,并且可能无法重现该错误。如果您可以发布可编译的重现案例,我很乐意进一步调查并更新答案。
| 归档时间: |
|
| 查看次数: |
459 次 |
| 最近记录: |