This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| STL Container Cleanup Submitted by

A lot of people use STL (Standard Template Library) template containers for their collections. So does my friend. He has more than ten instantiated templates of vectors, lists and other container templates.
The thing is that he stores pointers to base classes then makes some derive instances and stores the base pointer into the collection. Then the same old story ... polymorph...orph..
He new that when he cleared the containers with clear() method of the container pointers are not touched. (beware if you use your the same pointer in several different collection this can cause you trouble) So, he had to write a boring cycle for every single collection to delete all pointers residing there.
So was born our templatized "stlwipe" function which looks like this:

    template<class T
    void stlwipe(T &t)
    {
    	//get the first iterator
    	T::iterator i=t.begin();

    	//iterate to the end and delete items (should be pointers)
    	for(; i!=t.end();++i) delete(*i);

    	//clear the collection (now full with dead pointers)
    	t.clear();
    }

The only thing the programmer does is calling the "stlwipe" function with parameter the container itself... the template is implicitly instantiated and your collection is successfully wiped (with proper virtual destructors called)
An example:

    vector<Base * vpBase;
    vpBase.push_back(new Derived());
    vpBase.push_back(new Derived2());
    vpBase.push_back(new Derived3());

    //wipe it out
    stlwipe(vpBase);

Simple isnt it?
To be honest here is what Bruce Eckel (Thinking in C++) wrote about this:

    // Template function:
    template <class T
    void wipe(T* x) { delete x; }

    //then you simply do
    for_each(vpBase.begin(), vpBase.end(), wipe<Base);

In this case you should know what is the type of the contained elements while in our function you simply pass the container it self and it does it for you.
:)
Kind regards,
Yordan (WarJo) Gyurchev

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.