I’ve got a std::map:
std::map<std::string, std::string>
I’m passing string literal to find method. Obviously, I can pass a string literal such as
.find("blah");
However, I wanted to declare it upfront, instead of hardcoding the string, so I have couple of choices now:
const std::string mystring = "blah";
const char mystring[] = "blah";
static const char * mystring = "blah";
They all work. (or at least compile). My question is, which one should I use? what’s the advantage/distavantage over of the other?
Advantages and disadvantatges:
const std::string mystring = "blah";This is pretty much the standard C++ way to deal with strings. You can do about anything you’d ever need to do with a string with this. The main disadvantage is that it is slower. There is a dynamic allocation in there. Also, if
.findrelies onchar[]under the scenes, you are wasting all that heap work, and it may even have to do more to get the c-usable array internally.const char mystring[] = "blah";This allocates your 5-byte string on the stack, so it is nice and fast. The disadvantage is that if
.finduses std::string, it is going to have to do that allocation anyway, and it will do it every call instead of just once here. Also, if you ever have to do anything else with it (eg: catenate “.txt” to it), it would have been far easier to do with a std::string.static const char * mystring = "blah";If this is in outer scope, this means it stays local to your source file. The C++ way to do this is with unnamed namespaces instead of
staticthough. The only advantage to doing it this way is that it is compatible with C (or at least with new enough compilers that know what “const” is).Generally, I’d go with std::string. Except in special or extreme cases, ease of use trumps speed.