views:

152

answers:

2

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

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

I know char*'s are usually defined on the stack, so we know exactly how much memory we'll use, is this actually a good argument for their use? Or is std::string better in every way?

+3  A: 

If you're writing in C++ then std::string will be better in most cases you'll encounter. Instead, a few cases when you might want to use char*'s:

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

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

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

Frequency
+2  A: 

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

  1. Talking to the OS, but usually, if you're passing the string to the OS then std::string::c_str has it covered
  2. Constants - std::string is a bit heavy weight for constant strings since it will do a heap allocation at app startup

Obviously there are exceptions to every rule. If you're doing a lot of text parsing then using raw pointers into buffers can be more efficient for example, but for general string fiddling std::string is preferred.

Stewart