开发者

C++: Should I use strings or char arrays, in general?

I'm a bit fuzzy on the basic ways in which programmers code differently in C and C++. One thing in particular is the usage of strings in C++ over char arrays, or v开发者_JAVA百科ice versa. So, should I use strings or char arrays, in general, and why?


In C++ you should in almost all cases use std::string instead of a raw char array.

std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it.

It also provides a much easier to use and more readable interface for common string operations, e.g. equality testing, concatenation, substring operations, searching, and iteration.


If you're modifying or returning the string, use std::string. If not, accept your parameter as a const char* unless you absolutely need the std::string member functions. This makes your function usable not only with std::string::c_str() but also string literals. Why make your caller pay the price of constructing a std::string with heap storage just to pass in a literal?


Others have put it. Use the std::string stuff wherever possible. However there are areas where you need char *, e.g if you like to call some system-services.


As is the case with everything what you choose depends on what you're doing with it. std::string has real value if you're dealing with string data that changes. You can't beat char[] for efficiency when dealing with unchanging strings.


Use std::string. You will have less problems (I think almost none, at least none come to my mind) with buffer sizes.


C has char[] while c++ has std::string too...

I commonly hear that one should "Embrace the language" and, following that rule, you should use std::string...

However, its pretty much up to what library are you using, how does that library want you to express your strings, stuff like that.

std::string is a container class, and inside it, is a char[]
If you use std::string, you have many advantages, such as functions that will help you [compare, substr, as examples]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜