wrote:
> Hi,
>
> I have the following code which frees memory allocate by a STL vector,
> vector of vector, map of vector.
> I would like to know if I indeed free all the memory (i.e. no memory
> leak).
>
> Thanks for any advice:
> /* From Effective STl */
> struct DeleteObject {
>
> template<typename T>
> void operator()(const T* ptr) const {
> delete ptr;
> }
> };
>
> typedef vector<A*> AVector;
> // free a vector of 'A*'
> void f4(AVector& aVector) {
> for_each(aVector.begin(), aVector.end(), DeleteObject());
> aVector.clear();
> }
>
>
> // free a vector of vector of 'A*'
> void f4(vector<AVector*>& aVectorVector) {
> for(vector<AVector*>::iterator itr = aVectorVector.begin(); itr !=
> aVectorVector.end(); ++itr) {
> AVector* aVector = (*itr);
> f4( *aVector);
> }
> aVectorVector.clear();
> }
>
> // free a map of vector of 'A*'
> void f4(map<int, AVector*>& aMapVector) {
> for(map<int, AVector*>::iterator itr = aMapVector.begin(); itr !=
> aMapVector.end(); ++itr) {
> AVector* aVector = (*itr).second;
> f4( *aVector);
> }
> aMapVector.clear();
> }
It's better and safer to use a smart pointer for this, than to use this
type of manual mememory management.
Anytime you have to make explicit calls to clear your memory, you're
only asking for memory leaks.
Consider using boost::shared_ptr, or one of the following smart
pointers:
http://code.axter.com/cow_ptr.h
http://code.axter.com/copy_ptr.h
http://code.axter.com/smart_ptr.h
vector<cow_ptr<AVector> > MyvA;
vector<smart_ptr<AVector> > MyvA;
vector<boost::shared_ptr<AVector> > MyvA;
The code is free, and so as boost code, and you don't have to worry
about memory leaks.