0

I've made quite a few projects (small) now with C++ and was wondering, what would be some good scenarios in which it is better to use a cstring instead of a string?

Just to clarify, I'm not calling cstrings bad. I'm just genuinely interested if they are as important as regular strings in C++

W3S4
  • 3
  • 1
  • 1
  • 3
    What do you mean by "cstring"? null-terminated `char` arrays? – UnholySheep Jul 09 '20 at 22:06
  • Possible duplicate of [Difference between string and char\[\] types in C++](https://stackoverflow.com/questions/1287306/difference-between-string-and-char-types-in-c) or [Difference between string and char\[\] types in C++](https://stackoverflow.com/questions/1287306/difference-between-string-and-char-types-in-c) or [What's the difference between std::string and std::basic_string? And why are both needed?](https://stackoverflow.com/questions/1662107/whats-the-difference-between-stdstring-and-stdbasic-string-and-why-are-bot). – Martin Konrad Jul 09 '20 at 22:44

2 Answers2

4

std::string allocates dynamic memory at runtime for its character data (unless the std::string implementation employs "Short String Optimization" and the data is short enough to fit in the SSO buffer).

So, one scenario you may want to use C-style strings for is when you want to pass around string literals without allocating memory for them. Assigning a string literal to a std::string will allocate dynamic memory (if SSO is not used).

There can also be scenarios where you want to process character data without allocating new memory for extracted substrings. C-style strings can be good for that, too (though std::string_view in C++17 and later would generally be better for that).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-1

cstrings are just character arrays will a null character to terminate them. While std::string are dynamically allocated. Able to have more memory control; basically memory management is the main advantage

Pavel
  • 72
  • 3
  • 1
    You may want to rethink this answer. The questioner is looking for cases where a cstring, presumably a null terminated character array is preferable to a string, presumably a `std::string`, not looking for the differences between the two or the advantages of `string` over `char` array. – user4581301 Jul 09 '20 at 22:55