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;
}

这是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的空间,即内存泄露问题得到解决(帅气的操作)。

上一篇 下一篇

猜你喜欢

热点阅读