当有关于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
#include
#include
#include
template
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
struct rebind {
typedef MyAllocator other;
};
MyAllocator() = default;
MyAllocator(MyAllocator&&) = default;
MyAllocator(MyAllocator const&) = default;
MyAllocator& operator=(MyAllocator&&) = default;
MyAllocator& operator=(MyAllocator const&) = default;
template
MyAllocator(MyAllocator 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(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 " <
free(p);
}
size_type max_size() const throw() { return std::numeric_limits::max() / sizeof(value_type); }
template
void construct(U* p, Args&&... args) { ::new ((void*)p) U (std::forward(args)...); }
template
void destroy(U* p) { p->~U(); }
};
template
using MyList = std::list>;
int main() {
MyList l;
l.push_back(1);
}