Possible Duplicate:
C++ char* vs std::string
I'm new to C++ coming from C# but I really do like C++ much better.
I have an abstract class that defines two constant strings (not static). And I wondered if a const char*
would be a better choice. I'm still getting the hang of the C++ standards, but I just figured that there really isn't any reason why I would need to use std::string in this particular case (no appending or editing the string, just writing to the console via printf
).
Should I stick to std::string
in every case?
Should I stick to std::string in every case?
Yes.
Except perhaps for a few edge cases where you writing a high performance multi-threaded logging lib and you really need to know when a memory allocation is going to take place, or perhaps in fiddling with individual bits in a packet header in some low level protocol/driver.
The problem is that you start with a simple char and then you need to print it, so you use printf(), then perhaps a sprintf() to parse it because std::stream would be a pain for just one int to string. And you end up with an unsafe and unmaintainable mix oc c/c++
There are cases where
std::string
isn't needed and just a plainchar const*
will do. However you do get other functionality besides manipulation, you also get to do comparison with other strings and char arrays, and all the standard algorithms to operate on them.I would say go with
std::string
by default (for members and variables), and then only change if you happen to see that is the cause of a performance drop (which it won't).This like comparing Apples to Oranges.
std::string
is a container class while char* is just a pointer to a character sequence.It really all depends on what you want to do with the string.
Std::string on the other hand can give you a quick access for simple string calculation and manipulation function. Most of those are simple string manipulation functions, nothing fancy really.
So it basically depends on your needs and how your functions are declared. The only advantage for std::string over a char pointer is that it doesnt require a specific lenghth decleration.
I would stick to using
std::string
instead ofconst char*
, simply because most of the built-in C++ libraries work with strings and not character arrays.std::string
has a lot of built-in methods and facilities that give the programmer a lot of power when manipulating strings.Use
std::string
when you need to store a value.Use
const char *
when you want maximum flexibility, as almost everything can be easily converted to or from one.