Legal to overwrite std::string's null terminator?

后端 未结 4 427
感动是毒
感动是毒 2020-12-01 09:11

In C++11, we know that std::string is guaranteed to be both contiguous and null-terminated (or more pedantically, terminated by charT(), which in t

4条回答
  •  忘掉有多难
    2020-12-01 09:36

    Unfortunately, this is UB, if I interpret the wording correct (in any case, it's not allowed):

    §21.4.5 [string.access] p2

    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.

    (Editorial error that it says T not charT.)

    .data() and .c_str() basically point back to operator[] (§21.4.7.1 [string.accessors] p1):

    Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

提交回复
热议问题