Char * vs std :: string

Possible duplicate:
C ++ char * vs std :: string

Is there any advantage to using char * instead of std :: string?

I know char * are usually defined on the stack, so we know exactly how much memory we will be using, is that really a good argument to use them? Or is std :: string better in every way?

+2


a source to share


2 answers


If you are writing in C ++ then std :: string will be better in most cases you come across. There are a few cases where you can use char *

instead : -Compatibility with old C code (although the std :: string c_str () method handles most of this)

- To save memory (std :: string will likely have more overhead expenses)

-Cases where you want to make sure you know where the memory is, like network code or shared memory



+4


a source


When working exclusively with C ++, std :: string is better in almost every way. The only cases in which I still use C strings are

  • Talking about the operating system, but usually if you are passing a string to the OS then std :: string :: c_str it covers
  • Constants - std :: string is a bit heavy weight for constant strings as it will do heap allocation when the app starts


Obviously, there are exceptions to every rule. If you do a lot of text parsing, then using raw pointers in buffers might be more efficient, for example, but for general use of strings, std :: string is preferred.

+2


a source







All Articles