Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

stdstring - When to use char array instead of strings in c++?

How do we differentiate char arrays and string in c++? Is there anything char arrays do better than std::string ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. Before C++20, std::string could not be used in constexpr context. So, I still prefer declaring global string constants with constexpr const char[] if all I do is just passing them to some function. As @HolyBlackCat mentioned in the comments, C++17 std::string_view makes this use-case obsolote too, especially with the new sv literal:

    #include <string_view>
    using namespace std::literals;
    //Compile-time string_view
    constexpr auto str = "hello"sv;
    
  2. const char* is somewhat more universal. You can pass it to a function accepting const char*, std::string, or std::string_view. The reverse requires std::string::c_str() and it is not possible to so without copying the std::string_view.

  3. There is no dynamic allocation involved. Although std::string might 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.

  4. Interacting with old libraries. But even then, std::string is 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...