In C++11, can the characters in the array pointed to by string::c_str() be altered?

后端 未结 4 748
情深已故
情深已故 2021-01-01 21:57

std::string::c_str() returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of t

4条回答
  •  星月不相逢
    2021-01-01 22:49

    In C++11, yes the restriction for c_str() is still in effect. (Note that the return type is const, so no particular restriction is actually required for this function. The const_cast in your program is a big red flag.)

    But as for operator[], it appears to be effect only due to an editorial error. Due to a punctuation change slated for C++14, you may modify it. So the interpretation is sort of up to you. Of course doing this is so common that no library implementation would dare break it.

    C++11 phrasing:

    Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.

    C++14 phrasing:

    Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

    You can pass c_str() as a read-only reference to a function expecting a C string, exactly as its signature suggests. A function expecting a read-write reference generally expects a given buffer size, and to be able to resize the string by writing a NUL within that buffer, which std::string implementations don't in fact support. If you want to do that, you need to resize the string to include your own NUL terminator, then pass & s[0] which is a read-write reference, then resize it again to remove your NUL terminator and hand the responsibility of termination back to the library.

提交回复
热议问题