A while ago I asked about std::string constants correct idiom for std::string constants?.
What I took away from that was not to use std::string constants but to use char string constants. So what the best idiom for that
#define FOO "foo"
const char * const FOO = "foo";
const char FOO[] = "foo";
Desirable features
- get length at compile time. 1 & 3 but
not 2 (sizeof doesnt work on 2) - can be included in .h without linker
complaining. all (I think) - no multiple copies in .o, in linked
output. depends on compiler
(probably)
So it seems like #3 is best but scott meyers says to use #2 (effective c++ item #1)
summary of answers
- use jolly complicated template code
- use #3
The template code feels like overkill. So for now I go with #3;
But I will ruminate on the template code, the macroized version makes it look OKish; but I dont like the fact that its not portable (who knows, maybe gcc will decide that its wrong too)
Your desired features are contradictory.
To get (1) and (2), you need to declare the variable as
staticor put it in an unnamed namespace. However, this will cause a definition in each compilation unit, which goes against (3).To get (2) and (3), you need to declare the variable as
extern, but then you won’t get (1).Now, if your linker is smart, it might optimize away the multiple copies, but I’m not sure if the standard allows it…
I recommend the
const char FOO[] = "foo";syntax declared in an unnamed namespace or asstaticif it need to be found in a specific namespace. If the string is very large, then I go for anextern.