tags:

views:

110

answers:

4

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?

+2  A: 

(This is assuming the key_type of your map is std::string)

I would go with an option you didn't specify:

static const std::string mystring("blah");

That way the string is both read-only and initialized only once.

fbrereto
A: 

I would prefer

 const char * const mystring = "blah"; 
Alexey Malistov
+6  A: 

Assuming your map is keyed by std::string (which I think it must be for all three choices to compile), then the first is more efficient. You'll make a single string object, and pass it by reference to each call to find. The others will cause a temporary string object to be created for each find.

Mike Seymour
+2  A: 

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 .find relies on char[] 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 .find uses 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 static though. 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.

T.E.D.
it's a map: std::map<std::string, std::string>, still not sure, whether it gets converted to char[]
ra170
If you don't know, I'd probably go with std::string.
T.E.D.