Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use const char * literal as a std::map key?

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.

like image 219
Martin Perry Avatar asked May 13 '17 09:05

Martin Perry


People also ask

Can a map key be char?

there is an implicit conversion from char* to std::string. You must not use char* as a map key.

Are map keys unique C++?

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.

Can you change the value of a key in a map C++?

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.

Why do we use const char?

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.


1 Answers

Is it safe to use const char * literal as a std::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.

like image 63
eerorika Avatar answered Sep 20 '22 18:09

eerorika