I have a map that represents a DB object. I want to get 'well known' values from it
std::map<std::string, std::string> dbo;
...
std::string val = map["foo"];
all fine but it strikes me that "foo" is being converted to a temporary string on every call. Surely it would be better to have a constant std::string (of course its probably a tiny overhead compared to the disk IO that just fetched the object but its still a valid question I think). So what is the correct idiom for std::string constants?
for example - I can have
const std::string FOO = "foo";
in a hdr, but then I get multiple copies
EDIT: No answer yet has said how to declare std::string constants. Ignore the whole map, STL, etc issue. A lot of code is heavily std::string oriented (mine certainly is) and it is natural to want constants for them without paying over and over for the memory allocation
EDIT2: took out secondary question answered by PDF from Manuel, added example of bad idiom
EDIT3: Summary of answers. Note that I have not included those that suggested creating a new string class. I am disappointed becuase I hoped there was a simple thing that would work in header file only (like const char * const ). Anyway
a) from Mark b
std::map<int, std::string> dict;
const int FOO_IDX = 1;
....
dict[FOO_IDX] = "foo";
....
std:string &val = dbo[dict[FOO_IDX]];
b) from vlad
// str.h
extern const std::string FOO;
// str.cpp
const std::string FOO = "foo";
c) from Roger P
// really you cant do it
(b) seems the closest to what I wanted but has one fatal flaw. I cannot have static module level code that uses these strings since they might not have been constructed yet. I thought about (a) and in fact use a similar trick when serializing the object, send the index rather than the string, but it seemed a lot of plumbing for a general purpose solution. So sadly (c) wins, there is not simple const idiom for std:string
See Question&Answers more detail:os