STL内存分配方式

  关于STL用的很多比如map, vector, set, queue, stack等等。很少关注它的内存分配情况,但是经常遇到比如使用map,不停的在map中插入了一些很小的对象,然后释放了一些,然后想要再申请的时候出现了OutOfMemory的错误;

这是由于内存碎片化导致的。

  STL分配内存的工具是allocator, 根据c++标准把对象的申请分为了4步:

  第一步,申请内存空间,对应的函数式alloctor::allocate()

  第二步,执行构造函数,对应的函数式alloctor::construct()

  第三步,执行析构函数,对应的函数式alloctor::destory()

  第四步,释放内存空间,对应的函数式alloctor::deallocate()

  我们可以指定要使用的allocator :
  map<int, int, less<int>, std::allocator<pair<int, int>>>mp;

  map<int, int, less<int>, __gnu_cxx::new_allocator<pair<int, int>>>mp;

原文地址:https://www.cnblogs.com/luntai/p/6472075.html