Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string vs char array for static const

Tags:

c++

arrays

static

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 since it "avoids static allocation". Doesn't the char array also have to be statically allocated?

like image 523
theraju Avatar asked Dec 20 '22 03:12

theraju


1 Answers

Yes, yes it does also have to be statically allocated.

Always use std::string unless your profiler tells you that it's worth pissing around with legacy crap like const char[]. Choosing const char[] is an annoying micro-optimization over std::string and a stupid decision unless you know for sure that this piece of code is a hotpath (since it's static either way I highly doubt it).

like image 128
Puppy Avatar answered Jan 03 '23 15:01

Puppy