当有关于 STL 容器的内存问题时......请记住,它们获得的所有内存都来自您传递的分配器(默认为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);
}