C++ STL 中的map,vector等內存釋放問題是一個很令開發者頭痛的問題,關於
stl內部的內存是自己內部實現的allocator,關於其內部的內存管理本文不做介紹,只是
介紹一下STL內存釋放的問題:
記得網上有人說采用Sawp函數可以完全清除STL分配的內存,下面使用一段代碼來看看
結果:
首先測試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:
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的內存。
結論:
上面測試的結果:STL中的clear函數式完全不釋放內存的,vector使用swap可以釋放內存,map則不可以,貌似而STL保留了這部分內存,下次分配的時候會復用這塊內存。