Why use c strings in c++?

后端 未结 18 2173
终归单人心
终归单人心 2021-02-07 04:12

Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string

相关标签:
18条回答
  • 2021-02-07 04:34

    Given the choice, there is generally no reason to choose primitive C strings (char*) over C++ strings (std::string). However, often you don't have the luxury of choice. For instance, std::fstream's constructors take C strings, for historical reasons. Also, C libraries (you guessed it!) use C strings.

    In your own C++ code it is best to use std::string and extract the object's C string as needed by using the c_str() function of std::string.

    0 讨论(0)
  • 2021-02-07 04:37

    Let's say you have some string constants in your code, which is a pretty common need. It's better to define these as C strings than as C++ objects -- more lightweight, portable, etc. Now, if you're going to be passing these strings to various functions, it's nice if these functions accept a C string instead of requiring a C++ string object.

    Of course, if the strings are mutable, then it's much more convenient to use C++ string objects.

    0 讨论(0)
  • 2021-02-07 04:37

    Legacy code that doesn't know of std::string. Also, before C++11 opening files with std::ifstream or std::ofstream was only possible with const char* as an input to the file name.

    0 讨论(0)
  • 2021-02-07 04:39

    If a function needs a constant string I still prefer to use 'const char*' (or const wchar_t*) even if the program uses std::string, CString, EString or whatever elsewhere.

    There are just too many sources of strings in a large code base to be sure the caller will have the string as a std::string and 'const char*' is the lowest common denominator.

    0 讨论(0)
  • 2021-02-07 04:40

    Because that's how they come from numerous API/libraries?

    0 讨论(0)
  • 2021-02-07 04:40

    1) "string constant" is a C string (const char *), converting it to const std::string& is run-time process, not necessarily simple or optimized. 2) fstream library uses c-style strings to pass file names.

    My rule of thumb is to pass const std::string& if I am about to use the data as std::string anyway (say, when I store them in a vector), and const char * in other cases.

    0 讨论(0)
提交回复
热议问题