The reason they did this is because it is dangerous. You must GUARANTEE that none of the std::string members will change, or the whole map becomes invalid. Interestingly, the first solution that comes to mind seems insanely hacked, and looks like UB, but I think that the UB skirt is very careful.
struct key_type { mutable const char* ptr; }; bool operator<(const key_type& lhs, const key_type& rhs) {return strcmp(lhs.ptr, rhs.ptr)<0;} struct person { std::string name; int age; }; person& people_map_get(std::map<key_type, person>& map, const char* name) { auto it = map.insert(name, person{name}).first;
As I hope, it is clear that this craziness is close to UB, and is highly discouraged. Basically, during input / search, key points on your temporary object or input line, and then, as soon as the object is inserted / found, the key is changed to indicate the value contained in the string member, and until you never do nothing to invalidate the .c_str() return value on any contained person object, everything just works. I think.
source share