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
- Talking to the OS, but usually, if you're passing the string to the OS then std::string::c_str has it covered
- 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.
精彩评论