Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct idiom for std::string constants?

Tags:

People also ask

What is the other name of string constant?

A String Literal, also known as a string constant or constant string, is a string of characters enclosed in double quotes, such as "To err is human - To really foul things up requires a computer." String literals are stored in C as an array of chars, terminted by a null byte.

Is std :: string literal?

std::string literals are Standard Library implementations of user-defined literals (see below) that are represented as "xyz"s (with a s suffix). This kind of string literal produces a temporary object of type std::string , std::wstring , std::u32string , or std::u16string , depending on the prefix that is specified.


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