How do we differentiate char arrays and string in c++? Is there anything char arrays do better than std::string ?
2 Answers
How do we differentiate char arrays and string in c++?
You don't, string literals are by definition null-terminated char arrays. Since arrays decay into pointers the first chance they get, const char* is (still) often a synonym for string.
If you are asking about when you should write new char[n], the answer is never. If anything, it should be std::make_unique<char[]>(n); and unless you are writing your own version of std::string, use the standard one. If you need a buffer, use std::vector or std::array.
There are some advantages of const char[] constants over const std::string but they are being "solved" by the new C++ Standards:
Before C++20,
std::stringcould not be used inconstexprcontext. So, I still prefer declaring global string constants withconstexpr const char[]if all I do is just passing them to some function. As @HolyBlackCat mentioned in the comments, C++17std::string_viewmakes this use-case obsolote too, especially with the newsvliteral:#include <string_view> using namespace std::literals; //Compile-time string_view constexpr auto str = "hello"sv;const char*is somewhat more universal. You can pass it to a function acceptingconst char*,std::string, orstd::string_view. The reverse requiresstd::string::c_str()and it is not possible to so without copying thestd::string_view.There is no dynamic allocation involved. Although
std::stringmight employ SSO, it is not guaranteed. This might be relevant for very small systems where the heap is precious and the program flash memory is more accomodating and contains the literal anyway.Interacting with old libraries. But even then,
std::stringis null-terminated too.
Overall, my recommendation would be to use std::string_view every chance you get - for any non-owning string, including holding string literals. Most importantly, it should replace const char* and const std::string& function parameters. If you want to own a string, use std::string.
2 Comments
string_view has a problem: if you then need to call a function that expects a read-only null-terminated string (e.g. third-party library), you have to copy the whole viewed string to add the terminator, even though the source for the string-view already had it. Which is a waste of time and resources.std::string_view can do non-suffix-based substrings without copy, which ordinary read-only null-terminated string cannot.One reason (which I personally don't think is a very good one) to use char arrays is the use case when you want your code to compile with both a C compiler and a C++ compiler.
std::stringcannot be used inconstexprcontext before C++20, so I still preferconst char[]for global constants unless I need to do some string operations with them.constexprstring_views should also work. Voted to reopen.