- when using containers of newed pointers, remember to delete the pointers before the container is destroyed.
void doSomething() {
vector<Widget*> vwp;
for(int i=0;i<NUMS;++i) {
vwp.push_back(new Widget);
}
}
// Widgets are leaked here !
- you should delete the memory which you allocate
void doSomething() {
vector<Widget*> vwp;
for(int i=0;i<NUMS;++i) {
vwp.push_back(new Widget);
}
//////// do something
for(vector<Widget*>::iterator it=vwp.begin(); it!=vwp.end(); ++it) {
delete *it;
}
}
- you can also use for_each to free the memory
template<typename T>
struct DeleteObject {
public unary_function<const T*, void> {
void operator()(const T *ptr) const {
delete ptr;
}
}
};
Now you can do this:
void doSomething() {
... // as before
for_each(vwp.begin(), vwp.end(), DeleteObject<Widget>);
}
- you can also use another defination to simplify the maintain
struct DeleteObject {
template<typename T>
void operator()(const T* ptr) const {
delete ptr;
}
};
void doSomething() {
deque<SpecialString*> dssp;
... //fill the containers
for_each(dssp.begin(), dssp.end(), DeleteObject());
// ah! well-defined behavior, Straightforward and type-safe, just the wat we like it.
}
- Use Smart Pointer to revoke the memory
void doSomething() {
typedef std::shared_ptr<Widget> SPW;
vector<SPW> vwp;
for(int i=0;i<NUMS;++i) {
vwp.push_back(SPW new Widget);
}
}
// No Widgets are leaked here, not even if an exception is thrown in the code above