清除vector中的非smartpointer

来源:互联网 发布:mysql emoji 截断 编辑:程序博客网 时间:2024/06/08 05:11

容器一大坑,对放入的指针没有所有权。如果用户不自己释放,将引起内存泄漏。
例程如下:

    class Counted {        int id;        static int count;    public:        Counted() :id(count++) {            cout << "Counted id = " << id << ends;            cout << "  it's created" << endl;        };        ~Counted() {            cout << "Counted id = " << id << ends;            cout << "  it's destroyed" << endl;        }    };    int Counted::count = 1;

丑陋的版本

    vector<Counted*>v_co;    for (int i = 0; i < 20; i++) {        v_co.push_back(new Counted());    }    vector<Counted*>::iterator it = v_co.end();    --it;    while (it >= v_co.begin()) {        delete *it;        if (it != v_co.begin())            it--;        else            break;    }    v_co.clear();    cout << v_co.size() << endl;

这里用rbegin() 与 rend()会优雅点,另外这两个迭代器属于不同的类型。

    auto it = v_co.rbegin();    while (it != v_co.rend()) {        delete *it;        it++;    }    v_co.clear();    cout << v_co.size() << endl;