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.
there is an implicit conversion from char* to std::string. You must not use char* as a map key.
All the elements of the set are unique. A map data structure in C++ is a structure in which the list is a hash of key/value pairs, stored in ascending order of keys by default, or in descending order of keys by programmer's choice. The keys are also unique, and there can be duplicated values.
A C++ STL map is used to store and manage key-value pairs. The elements are maintained in the sorted order of the keys. The keys in a map cannot be changed. Either a new key-value pair can be added or the value of an already existing key-value pair can be changed.
When you say const char *c you are telling the compiler that you will not be making any changes to the data that c points to. So this is a good practice if you will not be directly modifying your input data. As well as telling the compiler, it's also a helpful hint to the user of the API.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With