Why is sizeof(std::stack<int>) so large?

Viewed 124

In gcc I measured sizeof(std::stack<int>) and it show 80 bytes. Why it is so large?

It can contain pointer to the top and the size. Even if it contain also the pointer to the allocator, it should be not more than 20 bytes.

Another example, sizeof(std::set<int>) is 48 bytes.

1 Answers

You know you can read the source yourself, right?

class stack has a single member, a _Sequence which is a type alias for std::deque<_Tp> (and _Tp is int).

Off to the implementation of std::deque: that is just a wrapper around _Deque_base, which is a wrapper around _Deque_impl. That in turn holds a _Deque_impl_data, and finally we arrive at the following:

struct _Deque_impl_data {
    _Map_pointer _M_map;
    size_t _M_map_size;
    iterator _M_start;
    iterator _M_finish;
...
};

where iterator is a _Deque_iterator with the following members:

struct _Deque_iterator {
...
      _Elt_pointer _M_cur;
      _Elt_pointer _M_first;
      _Elt_pointer _M_last;
      _Map_pointer _M_node;
...
}

Summing it all up: each iterator holds 4 pointers (=32 bytes in a 64-bit system), and then _Deque_impl_data holds another two pointers, for a total of 80 bytes.

Related