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保留了這部份內存,下次分配的時候會複用這塊內存。