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