std :: list中每个元素的大小是多少?

时间:2013-04-11 04:47:25

标签: c++ stl

std :: list在其实现中使用链表,列表中的每个元素有多大(减去有效负载)?

通过测试,在Windows 7机器上使用mingw(而不是mingw-64),每个元素占用int的每个元素24个字节。

指向左侧的指针和指向右侧的指针只有4 + 4 = 8个字节!并且int只有4个字节(由sizeof(void *)和sizeof(int)确定),所以我很好奇,还有额外的空间吗?

(测试涉及制作许多元素,查看程序的大小,制作更多元素并再次查看程序的大小,取决于差异)

1 个答案:

答案 0 :(得分:8)

当有关于STL容器的内存问题时......请记住,他们获取的所有内存都来自您传递的 allocator (默认为std::allocator)。

因此,只需检测分配器即可回答大多数问题。实时演示位于liveworkspace,此处的输出显示为std::list<int, MyAllocator>

allocation of 1 elements of 24 bytes each at 0x1bfe0c0
deallocation of 1 elements of 24 bytes each at 0x1bfe0c0

因此,在这种情况下,24字节,在64位平台上是预期的:下一个和前一个的两个指针,4个字节的有效负载和4个字节的填充。


完整的代码清单是:

#include <iostream>
#include <limits>
#include <list>
#include <memory>

template <typename T>
struct MyAllocator {
   typedef T value_type;
   typedef T* pointer;
   typedef T& reference;
   typedef T const* const_pointer;
   typedef T const& const_reference;
   typedef std::size_t size_type;
   typedef std::ptrdiff_t difference_type;

   template <typename U>
   struct rebind {
      typedef MyAllocator<U> other;
   };

   MyAllocator() = default;
   MyAllocator(MyAllocator&&) = default;
   MyAllocator(MyAllocator const&) = default;
   MyAllocator& operator=(MyAllocator&&) = default;
   MyAllocator& operator=(MyAllocator const&) = default;

   template <typename U>
   MyAllocator(MyAllocator<U> const&) {}

   pointer address(reference x) const { return &x; }
   const_pointer address(const_reference x) const { return &x; }

   pointer allocate(size_type n, void const* = 0) {
      pointer p = reinterpret_cast<pointer>(malloc(n * sizeof(value_type)));
      std::cout << "allocation of " << n << " elements of " << sizeof(value_type) << " bytes each at " << (void const*)p << "\n";
      return p;
   }

   void deallocate(pointer p, size_type n) {
      std::cout << "deallocation of " <<n << " elements of " << sizeof(value_type) << " bytes each at " << (void const*)p << "\n";
      free(p);
   }

   size_type max_size() const throw() { return std::numeric_limits<size_type>::max() / sizeof(value_type); }

   template <typename U, typename... Args>
   void construct(U* p, Args&&... args) { ::new ((void*)p) U (std::forward<Args>(args)...); }

   template <typename U>
   void destroy(U* p) { p->~U(); }
};

template <typename T>
using MyList = std::list<T, MyAllocator<T>>;

int main() {
   MyList<int> l;
   l.push_back(1);
}