ryanbowen
ryanbowen

Reputation: 23

out_of_range using std::map::at(const char*) except when compiling with /02

I have a strange problem that I can't seem to make any headway on. I have a

std::unordered_map<char*, MyType>

that whenever I attempt to access with

at(const char*)

throws an out_of_range exception despite certainly containing the supplied key.

The only way it doesn't throw this exception is when built with /02 (Optimize for Speed), which is discovered when going to back debug and changing the optimization flag to disabled.

When I break at the place where I use at(), and look at my map, it looks perfectly fine, and the key is there, but the exception is still thrown.

Anyone ever have any issues like this?

std::unordered_map<char*, GUISetting> objectSettings = {{"Loot Containers", GUISetting("Loot Containers", LootContainerNames, true)}};

UI.objectSettings.at("Loot Containers").Enabled = iniReader.ReadBoolean("ObjectESP", "LootContainers", true);

Upvotes: 0

Views: 378

Answers (2)

j2ko
j2ko

Reputation: 2539

Additional to @tuple_cat answer you could place all your string constants in one place:

common_const.h:

extern const char LOOT_CONTAINERS[];
extern const char SOMETHING_ELSE[];

common_const.cc:

const char LOOT_CONTAINERS[] = "Loot Containers";
const char SOMETHING_ELSE[] = "Something Else";

And then use this constants instead across code. Similar approach used in Chromium sources. But this will not work if you will try to somehow get the key from user input or any other source. Alternatively you could use std::unordered_map<std::string, GUISetting>.

Upvotes: 0

flogram_dev
flogram_dev

Reputation: 42858

std::unordered_map compares the keys using ==, so it's checking whether your char pointers point to the same memory location, not that they point to equal strings.

If you want std::unordered_map to compare the strings that the char pointers point to, you need to pass the map a custom comparator as a template parameter. Or do it the easy way and use std::string as the key type.

Upvotes: 4

Related Questions