Which is better for string literals,
standard string or character array?
I mean to say for constant strings, say
const char name[] = "so"; //or to use
const string name = "so";
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For string literals, and only for string constants that come from literals, I would use
const char[]. The main advantage ofstd::stringis that it has memory management for free, but that is not an issue with string literals.It is the actual type of the literal anyway, and it can be directly used in any API that requires either the old C style null terminated strings or the C++ strings (implicit conversion kicks in). You also get a compile time size implementation by using the array instead of the pointer.
Now, when defining function interfaces, and even if constants are intented to be passed in, I would prefer
std::stringrather thanconst char*, as in the latter case size is lost, and will possibly need to be recalculated.Out of my own experience. I grew old of writting
.c_str()on each and every call to the logging library (that used variable arguments) for literal strings with info/error messages.