Mental Jetsam

By Peter Finch

C++ STL vector of pointers

Posted by pcfinch on October 11, 2010

Storing pointers in a C++ STL vector (e.g. vector<CBase *>) can be problematic, as you always have to remember to manually delete the pointers from the vector before deleting the vector, or before the vector goes out of scope. A simple way to get around the problem, is to subclass the vector template with another template and provide a destructor that deletes the contents of the array.

template<class _T> class prt_vector : public vector<_T*> {
public :
  virtual ~prt_vector() {
    for (unsigned int i=0; i<size(); i++) 
      delete (*this)[i] ;
  } ;
} ;

prt_vector<CBase> list ;
list.push_back(new CBase("Peter") ) ;
list.push_back(new CCake("Annette", "Fruit") ) ;

for (unsigned int i=0; i<list.size(); i++) {
  list[i]->print(cout) ; 

Storing pointers to the objects in the vector means you also get the added advantage of being able to store subclasses of the base class in the vector as well.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: