std::string vs. char*

前端 未结 3 509
滥情空心
滥情空心 2021-02-04 07:56

does std::string store data differently than a char* on either stack or heap or is it just derived from char* into a class?

3条回答
  •  [愿得一人]
    2021-02-04 08:28

    If you mean, does it store contiguously, then the answer is that it's not required but all known (to me, anyway) implementations do so. This is most likely to support the c_str() and data() member requirements, which is to return a contiguous string (null-terminated in the case of c_str())

    As far as where the memory is stored, it's usually on the heap. But some implementations employ the "Short String Optimization", whereby short string contents are stored within a small internal buffer. So, in the case that the string object is on the stack, it's possible that the stored contents are also on the stack. But this should make no difference to how you use it, since one the object is destroyed, the memory storing the string data is invalidated in either case.

    (btw, here's an article on a similar technique applied generally, which explains the optimization.)

提交回复
热议问题