1

The following code example that is here: http://coliru.stacked-crooked.com/a/c27c250819b72a01 shows 32 Bytes for std::string while 24 Bytes for std::vector<int>.

Though this may change from one platform to another, I expect to see sizeof std::string always larger than std::vector.

The question is why?

Evg
  • 25,259
  • 5
  • 41
  • 83
dwto
  • 278
  • 1
  • 7
  • 4
    What Sam refers to is that std::string already has a (not seperately allocated) for small strings, vector does not it only contains "metadata" and a pointer to a buffer. string will only start allocating on the heap when a string is too long to fit in the buffer. (called small string optimization). – Pepijn Kramer Jun 06 '23 at 13:16
  • 2
    The sentence should have started with : "What Sam refers to is that std::string already has buffer" – Pepijn Kramer Jun 06 '23 at 13:24
  • 1
    Libstdc++'s string is implemented as you'd expect and in the same way as vector with a pointer, a size and a capacity but for the small string optimisation string has an extra 8 bytes allowing storage of slightly larger strings before using the heap https://github.com/gcc-mirror/gcc/blob/ce2188e4320cbb46d6246bd3f478ba20440c62f3/libstdc%2B%2B-v3/include/bits/basic_string.h#L205 – Alan Birtles Jun 06 '23 at 14:03

0 Answers0