C++ - char* vs. string*

前端 未结 7 1527
清歌不尽
清歌不尽 2021-02-04 03:28

If I have a pointer that points to a string variable array of chars, is there a difference between typing:

char *name = \"name\";

7条回答
  •  不知归路
    2021-02-04 03:44

    char* name = "name" should be invalid but compiles on most systems for backward compatibility to the old days when there was no const and that it would break large amounts of legacy code if it did not compile. It usually gets a warning though.

    The danger is that you get a pointer to writable data (writable according to the rules of C++) but if you actually tried writing to it you would invoke Undefined Behaviour, and the language rules should attempt to protect you from that as much as is reasonably possible.

    The correct construct is

    const char * name = "name";
    

    There is nothing wrong with the above, even in C++. Using string is not always more correct.

    Your second statement should really be

    std::string name = "name";
    

    string is a class (actually a typedef of basic_string,allocator) defined in the standard library therefore in namespace std (as are basic_string, char_traits and allocator)

    There are various scenarios where using string is far preferable to using arrays of char. In your immediate case, for example, you CAN modify it. So

    name[0] = 'N';
    

    (convert the first letter to upper-case) is valid with string and not with the char* (undefined behaviour) or const char * (won't compile). You would be allowed to modify the string if you had char name[] = "name";

    However if want to append a character to the string, the std::string construct is the only one that will allow you to do that cleanly. With the old C API you would have to use strcat() but that would not be valid unless you had allocated enough memory to do that.

    std::string manages the memory for you so you do not have to call malloc() etc. Actually allocator, the 3rd template parameter, manages the memory underneath - basic_string makes the requests for how much memory it needs but is decoupled from the actual memory allocation technique used, so you can use memory pools, etc. for efficiency even with std::string.

    In addition basic_string does not actually perform many of the string operations which are done instead through char_traits. (This allows it to use specialist C-functions underneath which are well optimised).

    std::string therefore is the best way to manage your strings when you are handling dynamic strings constructed and passed around at run-time (rather than just literals).

    You will rarely use a string* (a pointer to a string). If you do so it would be a pointer to an object, like any other pointer. You would not be able to allocate it the way you did.

提交回复
热议问题