c语言中集合的长度,c – std :: list中每个元素的大小是多少?

当有关于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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值