char* vs std::string in c++


When should I use std::string and when should I use char* to manage arrays of chars in C++?

It seems you should use char* if performance(speed) is crucial and you're willing to accept some of a risky business because of the memory management.

Are there other scenarios to consider?

2/8/2015 9:23:54 PM

Accepted Answer

You can pass std::strings by reference if they are large to avoid copying, or a pointer to the instance, so I don't see any real advantage using char pointers.

I use std::string/wstring for more or less everything that is actual text. char * is useful for other types of data though and you can be sure it gets deallocated like it should. Otherwise std::vector is the way to go.

There are probably exceptions to all of this.

4/29/2009 7:20:41 AM

My point of view is:

  • Never use char * if you don't call "C" code.
  • Always use std::string: It's easier, it's more friendly, it's optimized, it's standard, it will prevent you from having bugs, it's been checked and proven to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow