Why does libc++'s implementation of std::string take up 3x memory as libstdc++?

后端 未结 4 1827
轻奢々
轻奢々 2020-11-30 07:09

Consider the following test program:

#include 
#include 
#include 

int main()
{
    std::cout << sizeof(st         


        
4条回答
  •  庸人自扰
    2020-11-30 07:32

    I haven't checked the actual implementations in source code, but I remember checking this when I was working on my C++ string library. A 24 byte string implementation is typical. If the length of the string is smaller than or equal to 16 bytes, instead of malloc'ing from the heap, it copies the string into the internal buffer of size 16 bytes. Otherwise, it mallocs and stores the memory address etc. This minor buffering actually helps in terms of running time performance.

    For some compilers, there's an option to turn the internal buffer off.

提交回复
热议问题