I'm using a std::map
with const std::string
keys, and I thought it would be nice to avoid pushing the keys all around the stack, so I changed the key type to pointer:
class less_on_star : less<const string*> {
public:
virtual bool operator() (const string* left, const string *right);
};
less_on_star::operator() (const string* left, const string *right) {
return *left < *right;
}
class Foo {
private:
map<const string*, Bar*, less_on_star> bars;
}
It worked fine for a while, then I started getting segfaults in which the string key had lost its guts. The _M_p
field pointed to NULL
or 0x2
, but the keys were always intact when I inserted into the map:
bars[new string(on_stack_string)] = bar;
In gdb it looked like new string(on_stack_string)
was pointing the _M_p
field to a normal heap location, not a stack value. Is there something special about std::string
that it can't be used in data structures like this? Maybe I did something else dumb with the keys, but I can't think what it would be.