Size of empty vector

半世苍凉 提交于 2019-12-04 18:50:17

Take a look at the sources. libstdc++ is part of the gcc download.

Anyway, the container must have these members:

  1. A data-pointer, 4 bytes for a char*.
  2. An element count or an end pointer, 4 bytes for a size_t or char*.
  3. A buffer-size or pointer to end-of-buffer, 4 bytes for a size_t or char*.
  4. The standard allocator (empty trivial type) needs no space, thanks to some implementation-tricks (Empty-baseclass-optimization, and perhaps partial template-specialization. C++20 could use the attribute [[no_unique_address]] instead).

In theory, 2 and 3 might be smaller if not pointers. Though that would be curious, as it would restrict the maximum size.

Also in theory, 2 and 3 could be allocated dynamically with the data. Haven't found anyone actually do that though.

Together 12 bytes, as expected.
Double the sizes for a 64-bit implementation.

Typically std::vector has:

1. Start of allocation / begin
2. End of vector (begin + size)
3. End of allocation (begin + capacity)

So size 12 is quite justified on a 32 bit machine.

libstdc++'s std::vector derived from a base with a data member of this type:

  struct _Vector_impl
  : public _Tp_alloc_type
  {
    pointer _M_start;
    pointer _M_finish;
    pointer _M_end_of_storage;
    ...

_M_end_of_storage supports .capacity() / resizing etc..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!