STL 内存释放

  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保留了这部分内存,下次分配的时候会复用这块内存。

上一篇:poj1065


下一篇:Requirejs之AMD规范