Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one to use const char[] or const std::string?

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";
like image 319
Passionate programmer Avatar asked Jan 20 '10 07:01

Passionate programmer


3 Answers

For string literals, and only for string constants that come from literals, I would use const char[]. The main advantage of std::string is 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::string rather than const 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.

like image 68
David Rodríguez - dribeas Avatar answered Nov 15 '22 05:11

David Rodríguez - dribeas


What are you doing with it? What do your methods expect?

const char is lighter in storage, but doesn't have the power of std::string, or the safety when using it. However, if you have a lot of C APIs, it may be the more judicious choice.

std::string would be the preferred option.

like image 25
Yann Ramin Avatar answered Nov 15 '22 06:11

Yann Ramin


You should use what is more appropriate for you. If no special requirements I'd use std::string because it do all memory work.

For string literals, I'd use const char*. The reason against const char[] is that you could use const char* to initialize another constant. Check the following code:

const char str1[] = "str1";
const char* str11 = "str11";

const char str2[] = str1;    // <<< compile error
const char* str22 = str11;   // <<< OK

String literals has static storage duration (according to 2.13.4/2) so pointer const char* will be valid until the completion of the program.

like image 33
Kirill V. Lyadvinsky Avatar answered Nov 15 '22 07:11

Kirill V. Lyadvinsky