Std :: string vs char array for static constant

I want to use a string constant in multiple places in my cpp file. Should I use std :: string or char []?

static const std::string kConstantString = "ConstantStringValue";

static const char kConstantString[] = "ConstantStringValue";

      

I was told to prefer the latter as it "avoids static allocation". Shouldn't you also statically allocate the char array?

+3


source to share


3 answers


Yes, yes, it must also be statically allocated.



Always use std::string

unless your profiler tells you to write with legacy shit like const char[]

. Choice const char[]

is an annoying micro-optimization versus std::string

and a silly decision unless you know for sure that this piece of code is a hotspot (since it's static anyway, I highly doubt it).

+7


source


Just define a pointer to that string literal. :) It can have a static storage specifier.



There is no need to use the std :: string class. It's just redundant and useless. This constant can always be converted to std :: string, if really needed.

+4


source


Since this is a static const

, you still won't be able to do any manipulation on that string, so it's better to just use const char[]

.

0


source







All Articles