Why Doesn't string::data() Provide a Mutable char*?

后端 未结 2 426
夕颜
夕颜 2020-12-11 14:57

In c++11 array, string, and vector all got the data method which:

Returns pointer to the underlyin

2条回答
  •  情歌与酒
    2020-12-11 15:35

    I think this restriction comes from the (pre-2011) days where std::basic_string didn't have to store its internal buffer as a contiguous byte array.

    While all the others (std::vector and such) had to store their elements as a contiguous sequence per the 2003 standard; so data could easily return mutable T*, because there was no problem with iterations, etc.

    If std::basic_string were to return a mutable char*, that would imply that you can treat that char* as a valid C-string and perform C-string operations like strcpy, that would easily turn to undefined behavior were the string not allocated contiguously.

    The C++11 standard added the rule that basic_string has to be implemented as a contiguous byte array. Needless to say, you can work-around this by using the old trick of &str[0].

提交回复
热议问题