Is it legal to write to std::string?

后端 未结 5 940
孤街浪徒
孤街浪徒 2020-12-03 21:21

In std::string there are only const members to fetch the data like c_str(). However I can get a reference to the first element of the string via operator[] and

5条回答
  •  失恋的感觉
    2020-12-03 21:56

    Herb Sutter has this to say (http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/#comment-483):

    current ISO C++ does require &str[0] to cough up a pointer to contiguous string data (but not necessarily null-terminated!), so there wasn’t much leeway for implementers to have non-contiguous strings, anyway. For C++0x we have already adopted the guarantee that std::string contents must indeed be stored contiguously. For details, see http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530

    And Matt Austern says similar in the referenced document (http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#530).

    So, it seems that you can assume that once you call str[0] you do get a modifyable array of characters (but note that it is not required to be null terminated).

提交回复
热议问题