相信搜索这个问题的大家已经知道vector的clear()只能对vector中的元素个数清空,但是并不能释放相应的空间。
swap 释放内存方法
网上有不少相关的文章介绍利用vector的swap()进行内存释放,总体上有两种方法:
以std::vector test(100,10);为例
方法一:std::vector().swap(test);
方法二:std::vector(test).swap(test);(实际上是不完整的)
但是这些博客没有说明两者的区别,使得刚接触这个问题的小伙伴们感到迷惑。
接下来我以一段实际的代码测试来阐述两者的区别:
code1:
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
std::vector<int> test(100,10);
cout<< test.size()<<endl;
cout << test.capacity()<<endl;
std::vector<int>().swap(test);
cout << test.size()<<endl;
cout << test.capacity()<<endl;
输出:
值得注意的是:这里在调用swap()之前,并不需要调用test.clear();
code2:
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
std::vector<int> test(100,10);
cout<< test.size()<<endl;
cout << test.capacity()<<endl;
std::vector<test>().swap(test);
cout << test.size()<<endl;
cout << test.capacity()<<endl;
输出:
分析:
这里把std::vector().swap(test)换成了std::vector(test).swap(test).跟上一段代码一样,这里在调用swap()之前没有调用clear().从输出结果来看,不能完成内存的释放。
code3:
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
std::vector<int> test(100,10);
cout<< test.size()<<endl;
cout << test.capacity()<<endl;
test.clear();
std::vector<test>().swap(test);
cout << test.size()<<endl;
cout << test.capacity()<<endl;
输出:
分析:从输出来看,很好的完成了内存释放。code3与code2的区别在于code3在调用swap()之前调用了clear().
结论:
所以code1与code3才是实现vector内存释放的正确方法。code1(方法一)的更加简明些,code2(方法二)要求先调用clear().
本文介绍了两种使用std::vector的swap()方法释放内存的有效方法。通过实际代码对比了不同方法的效果,明确了在何种情况下需要先调用clear()。
192

被折叠的 条评论
为什么被折叠?



