vector的内存泄露问题
2018-06-15 本文已影响0人
Hades灬指尖寒
最近在看STL 源码剖析关于vector这一部分的时候,书中有上面这样一段代码(只截取了书中代码的一部分),注释中的是运行到当前行的输出。(编译器使用的是GCC)
#include <iostream>
#include <vector>
using namespace std;
int main(){
int i = 0;
vector<int> iv(2, 9);
cout << "Size = " << iv.size() << endl; //Size = 2
cout << "Capacity = " << iv.capacity() << endl; //Capacity = 2
iv.push_back(1);
cout << "Size = " << iv.size() << endl; //Size = 3
cout << "Capacity = " << iv.capacity() << endl; //Capacity = 4
iv.push_back(2);
cout << "Size = " << iv.size() << endl; //Size = 4
cout << "Capacity = " << iv.capacity() << endl; //Capacity = 4
iv.clear();
cout << "Size = " << iv.size() << endl; //Size = 0
cout << "Capacity = " << iv.capacity() << endl; //Capacity = 4
return 0;
}
- 可以看到GCC中关于vector的自增长是采用增长为原来Capacity二倍的方式。(也在VS2017上测试了,是按原来Capacity的50%自增长的)
- 但我注意到:在对vector进程clear操作之后,capacity的大小依然没有变,即clear只是将size置为0,其占有的内存依然没有释放,这显然产生了内存泄露的问题,在网上查找了解决方法,作下记录:
这是C++标准关于vector().clear()的说明:
Clear content
Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:
vector<T>().swap(x); // clear x reallocating
使用swap后的结果:
vector<int>().swap(iv);
cout << "Size = " << iv.size() << endl; //Size = 0
cout << "Capacity = " << iv.capacity() << endl; //Capacity = 0
可以看到通过swap确实回收了内存,原因是:通过一个临时的空vector与原来的iv交换,临时对象占有原来iv的内存,然后临时对象消失、原来iv占有的内存被释放,现在iv占有的是capacity=0的空间,即内存泄露问题得到解决(帅气的操作)。