user3371868
user3371868

Reputation: 11

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

The Objectfactory class has a function called create() which returns a pointer to a class called 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.

Can anyone help me solve this problem? Thanks!

Upvotes: 1

Views: 1164

Answers (1)

juanchopanza
juanchopanza

Reputation: 227370

What happens if an entry with key "string" isn't in the map? You get an iterator to the end() element. 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. Otherwise, newObject is set to nullptr.

Upvotes: 2

Related Questions