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?

Community
  • 1
  • 1
Lockyer
  • 1,311
  • 1
  • 13
  • 30
  • Also, do you see the heap allocation of std::strings making any difference in real-time applications? – Lockyer Apr 27 '10 at 06:09
  • Sure, `char*` is better if you're a masochist. – rlbond Apr 27 '10 at 06:11
  • Ha, I generally prefer working with strings as well. However, I know people who prefer char*, I was curious if there was a good reason ;) – Lockyer Apr 27 '10 at 06:25

2 Answers2

4

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

Pete Schlette
  • 1,948
  • 1
  • 13
  • 18
2

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
  • 3,978
  • 17
  • 20