I have classes, each of them return its name
struct IFoo {
virtual const char * GetName() const = 0;
}
struct Foo : IFoo {
const char * GetName() const { return "Foo"; }
}
struct Bar: IFoo {
const char * GetName() const { return "Bar"; }
}
And somewhere else:
Foo* a = new Foo();
Foo* b = new Foo();
std::map<const char *, int> data;
data[a->GetName()] = 0;
printf("%i", data[b->GetName()]);
string literals should be stored in one place at memory, but is it 100%? This code works in gcc, but I am not sure of its multi-platformness.
Is it safe to use
const char *
literal as astd::map
key?
Yes.
However, consider that this is not guaranteed to find your object (but may, depending on implementation):
data["Foo"]
And this is guaranteed to not find your object:
char[] str = "Foo";
data[str];
Using a custom map comparator based on std::strcmp
would allow both of the above cases to work.
Then the only trap left is the possibility of storing a pointer to a local buffer into the map that would outlive the local buffer. That's not going to happen if you only store string literals of course, but that's something that you must remember to keep in mind when working with the map. A std::string
key would not have such caveat.