I\'m a C programmer trying to write c++ code. I heard string
in C++ was better than char*
in terms of security, performance, etc, however sometimes it
It's safer to use std::string
because you don't need to worry about allocating / deallocating memory for the string. The C++ std::string
class is likely to use a char*
array internally. However, the class will manage the allocation, reallocation, and deallocation of the internal array for you. This removes all the usual risks that come with using raw pointers, such as memory leaks, buffer overflows, etc.
Additionally, it's also incredibly convenient. You can copy strings, append to a string, etc., without having to manually provide buffer space or use functions like strcpy/strcat. With std::string it's as simple as using the =
or +
operators.
Basically, it's:
std::string s1 = "Hello ";
std::string s2 = s1 + "World";
versus...
const char* s1 = "Hello";
char s2[1024]; // How much should I really even allocate here?
strcpy(s2, s1);
strcat(s2, " World ");
Edit:
In response to your edit regarding the use of char*
in C++: Many C++ programmers will claim you should never use char*
unless you're working with some API/legacy function that requires it, in which case you can use the std::string::c_str()
function to convert an std::string
to const char*
.
However, I would say there are some legitimate uses of C-arrays in C++. For example, if performance is absolutely critical, a small C-array on the stack may be a better solution than std::string
. You may also be writing a program where you need absolute control over memory allocation/deallocation, in which case you would use char*
. Also, as was pointed out in the comments section, std::string
isn't guaranteed to provide you with a contiguous, writable buffer *, so you can't directly write from a file into an std::string
if you need your program to be completely portable. However, in the event you need to do this, std::vector
would still probably be preferable to using a raw C-array.
* Although in C++11 this has changed so that std::string
does provide you with a contiguous buffer