Deleting char* after assigning it to a string variable

后端 未结 3 683
夕颜
夕颜 2021-01-23 04:14

I have executed the below code and it works perfectly. Since it is about pointers, I just want to be sure. Though I\'m sure that assigning char* to string makes a copy and even

3条回答
  •  旧时难觅i
    2021-01-23 04:23

    There is no problem, as long as newChar points to a null-terminated string, and is not null itself.

    std::string has constructor that allows an implicit construction from a const char*. It makes a copy of the character string represented by the input const char * so it works under the assumption that the char* is a null terminated string, since there is no other way to know how many characters to copy into the string's own data storage. Furthermore, a NULL pointer is actually disallowed by the standard.

提交回复
热议问题