STL 内存释放

  C++ STL 中的map,vector等内存释放问题是一个很令开发者头痛的问题,关于函数

stl内部的内存是本身内部实现的allocator,关于其内部的内存管理本文不作介绍,只是测试

介绍一下STL内存释放的问题:spa

  记得网上有人说采用Sawp函数能够彻底清除STL分配的内存,下面使用一段代码来看看blog

结果:内存

首先测试vector:开发

void TestVector() {

  sleep(10);
  cout<<"begin vector"<<endl;
  size_t size = 10000000;
  vector<int> test_vec;
  for (size_t i = 0; i < size; ++i) {
        test_vec.push_back(i);
  }
  cout<<"create vector ok"<<endl;
  sleep(5);
  cout<<"clear vector"<<endl;
  // 你以为clear 它会下降内存吗?
  test_vec.clear();
  sleep(5);
  cout<<"swap vector"<<endl;
  {
        vector<int> tmp_vec;
        // 你以为swap它会下降内存吗?
        test_vec.swap(tmp_vec);
  }
  sleep(5);
  cout<<"end test vector"<<endl;
}

 结果显示:调用clear函数彻底没有释放vector的内存,调用swap函数将vector的内存释放完毕。内存管理

再来看看map:class

void TestMap() {

  size_t size = 1000000;
  map<int, int> test_map;
  for (size_t i = 0; i < size; ++i) {
        test_map[i] = i;
  }
  cout<<"create map ok"<<endl;
  sleep(5);
  cout<<"clear map"<<endl;
  // 你以为clear 它会下降内存吗?
  test_map.clear();
  sleep(5);
  cout<<"swap map"<<endl;
  {
         // 你以为swap它会下降内存吗?
        map<int,int> tmp_map;
        tmp_map.swap(test_map);
  }
  sleep(5);
  cout<<"end test map"<<endl;
}

  结果显示:调用clear函数彻底没有释放map的内存,调用swap函数也没有释放map的内存。test

结论:map

上面测试的结果:STL中的clear函数式彻底不释放内存的,vector使用swap能够释放内存,map则不能够,貌似而STL保留了这部份内存,下次分配的时候会复用这块内存。