简体   繁体   English

调试断言失败:映射/设置迭代器不可取消

[英]Debug Assertion Failed: map/set iterator not dereferencable

I'm working on a project, and as part of it I need to create a map with the first value as a string, and the second is a pointer to a class. 我正在开发一个项目,作为项目的一部分,我需要创建一个映射,第一个值为字符串,第二个为指向类的指针。

So I declared it map <string, Objectfactory*> Objlib 所以我声明了它map <string, Objectfactory*> Objlib

The Objectfactory class has a function called create() which returns a pointer to a class called Object . Objectfactory类具有一个名为create()的函数,该函数返回指向名为Object的类的指针。

So I have the following code: 所以我有以下代码:

Object* newobject = (*Objlib.find("string")).second->create();

The program compiles just fine, but I get a run time error at that line of code saying that the map/set iterator is not dereferencable. 该程序编译得很好,但是我在那行代码中遇到了运行时错误,指出map / set迭代器不可取消。

Can anyone help me solve this problem? 谁能帮我解决这个问题? Thanks! 谢谢!

What happens if an entry with key "string" isn't in the map? 如果键"string"的条目不在地图中,该怎么办? You get an iterator to the end() element. 您将获得一个end()元素的迭代器。 You can't de-reference that. 您不能取消引用它。

So, check if your map contains the element before de-referencing: 因此,请在取消引用之前检查地图是否包含元素:

auto it = Objlib.find("string");
Object* newObject = it == Objlib.end() ? nullptr : it->second->create();

This calls the create() method only if the element exists in the map. 仅当元素存在于地图中时,才调用create()方法。 Otherwise, newObject is set to nullptr . 否则,将newObject设置为nullptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM