Why are std::vector::data and std::string::data different?

后端 未结 4 2058
离开以前
离开以前 2020-12-03 09:35

Vector\'s new method data() provides a const and non-const version.
However string\'s data() method only provides a const version.

I th

4条回答
  •  执笔经年
    2020-12-03 10:13

    Although I'm not that well-versed in the standard, it might be due to the fact that std::string doesn't need to contain null-terminated data, but it can and it doesn't need to contain an explicit length field, but it can. So changing the undelying data and e.g. adding a '\0' in the middle might get the strings length field out of sync with the actual char data and thus leave the object in an invalid state.

提交回复
热议问题