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

后端 未结 4 2069
离开以前
离开以前 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:32

    Historically, the string data has not been const because it would prevent several common optimizations, like copy-on-write (COW). This is now, IIANM, far less common, because it behaves badly with multithreaded programs.

    BTW, yes they are now required to be contiguous:

    [string.require].5: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().

    Another reason might be to avoid code such as:

    std::string ret;
    strcpy(ret.data(), "whatthe...");
    

    Or any other function that returns a preallocated char array.

提交回复
热议问题