导致 sizeof() 为 32 的字符串结构中的开销是多少?
Most modern std::string
implementations1 save very small strings directly on the stack in a statically sized char
array instead of using dynamic heap storage. This is known as Small (or Short) String Optimisation (SSO). It allows implementations to avoid heap allocations for small string objects and improves locality of reference.
此外,还将有一个std::size_t
成员保存字符串大小和指向实际的指针char
贮存。
具体实现方式有所不同,但大致如下:
template <typename T>
struct basic_string {
char* begin_;
size_t size_;
union {
size_t capacity_;
char sso_buffer[16];
};
};
在典型的架构中sizeof (void*)
= 8,这给了我们 32 字节的总大小。
1 The “big three” (GCC’s libstdc++ since version 5, Clang’s libc++ and MSVC’s implementation) all do it. Others may too.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)