Where to use std::string
and where to use '\0'
terminated C-string.
Basically I want to know what edges they have over each other.

- 203,559
- 14
- 181
- 302

- 974
- 1
- 13
- 22
-
7use `std::string` all the time, and if you need a null terminated string (for example when using a C API) call the `c_str()` method. – Borgleader Feb 06 '14 at 06:17
-
[duplication?](http://stackoverflow.com/questions/4418708/whats-the-rationale-for-null-terminated-strings?rq=1) – AlexT Feb 06 '14 at 07:21
2 Answers
c++ std::string:
strings, overall, are more secure then char*, Normally when you are doing things with char* you have to check things to make sure things are right, in the string class all this is done for you. Usually when using char*, you will have to free the memory you allocated, you don't have to do that with string since it will free its internal buffer when destructed. Strings work well with c++ stringstream, formated IO is very easy.
char
Using char* gives you more control over what is happening "behind" the scenes, which means you can tune the performance if you need to.

- 1,342
- 12
- 31
-
2zero terminated strings are not that good in performance critical applications - consider complexity of strlen() or strcat() – AlexT Feb 06 '14 at 07:19
-
1Actually, tuning performance is a lot easier with a custom string class. `char*` is hardly tunable. The main reason is that string performance is affected by locality of reference, and therefore the Small String Optimalisation is the most important tool. Note that many implementations of `std::string` already have SSO. Even if not tuned specifically for your usage, it still beats `char*` which has no SSO at all. – MSalters Feb 06 '14 at 09:36
-
@MSalters What implementations have SSO? I don't think it's such a guaranteed win as to win over the majority. But anyway, "tune" is a buzzword that can usually be assumed to squelch its enclosing argument. – Potatoswatter Feb 06 '14 at 10:41
-
AFAIK MSVC has, and the proposed new GCC string class (which isn't used yet because adding SSO obviously breaks the ABI) – MSalters Feb 06 '14 at 14:20
zero terminated char* is used with C interfaces and std::string - in common c++ code. But there are not the only options - if you are really performance aware you may want to write your own string class (e.g. fixed length without dynamic memory allocation)

- 1,413
- 11
- 11