开发者

Char* vs std::string [duplicate]

开发者 https://www.devze.com 2022-12-28 12:17 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: C++ char* vs std::string
This question already has answers here: Closed 12 years ago.

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 memor开发者_高级运维y we'll use, is this actually a good argument for their use? Or is std::string better in every way?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号