Published

02 May 2014

Tags

Contents

一直对 stl 里的内存申请机制感到不解,写了这么一段代码做测试 :

#include <vector>
#include <iostream>
#include <ctime>

using namespace std;

struct fly {
    static int hh;
    int x;
    
    fly() {
        x = hh++;
    }
    
};

int fly::hh = 0;

int main() {
    vector<fly> a;
    int n = 1000000;
    a.resize(n);
    long long tt;
    int s=0;

    tt = clock();
    for (int i=0; i<1000; i++) {
        a.clear();
        a.resize(n);
        s += a[0].x;
    }
    cout << clock() - tt << endl;

    tt = clock();
    for (int i=0; i<1000; i++) {
        vector<fly> a;
        a.clear();
        a.resize(n);
        s += a[0].x;
    }
    cout << clock() - tt << endl;

    tt = clock();
    for (int i=0; i<1000; i++) {
        fly* a = new fly[n];
        s += a[0].x;
        delete[] a;
    }
    cout << clock() - tt << " " << s << endl;
}

运行结果三个耗时依次是 662, 1534, 2856, 结果令我很意外。

仔细的看了下 c++ reference, 发现所有 stl 容器里有一个不为人知的东西, allocator

似乎和我们平时理解的 new 不太一样,平时 new 一个元素,会首先为这个元素分配空间再调用构造函数, 而 allocator 则将这两部分开了, 有可能分配了空间却没有构造这个元素, 也有可能析构掉这个元素以后没有释放空间, 于是乎就出现了以上奇怪的运行结果。



blog comments powered by Disqus