Storing Pointers in a vector


For efficiency or other reasons, you can't store copies of your objects in a vector, but you need to keep track of them somehow.


Store pointers to your objects in a vector instead of copies of the objects themselves. But if you do, don't forget to delete the objects that are pointed to, because the vector won't do it for you. Example 6-4 shows how to declare and work with vectors of pointers.

Example 6-4. Using vectors of pointers


using namespace std;

static const int NUM_OBJECTS = 10;

class MyClass { /*...*/ };

int main( ) {

 vector vec;

 MyClass* p = NULL;

 // Load up the vector with MyClass objects
 for (int i = 0; i < NUM_OBJECTS; i++) {
 p = new MyClass( );

 // Do something useful with this data, then delete the objects when
 // you're done
 for (vector::iterator pObj = vec.begin( );
 pObj != vec.end( ); ++pObj) {
 delete *pObj; // Note that this is deleting what pObj points to,
 // which is a pointer

 vec.clear( ); // Purge the contents so no one tries to delete them
 // again



You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this:

vector vec;

The important thing to remember is that a vector stores values without regard for what those values represent. It, therefore, doesn't know that it's supposed to delete pointer values when it's destroyed. If you allocate memory, then put pointers to that memory in a vector, you have to delete the memory yourself when you are done with it. Don't be fooled by the term "container" into thinking that somehow when you store a pointer in a vector that it assumes ownership.

You should also explicitly empty the vector after you have deleted the pointers for the same reason that you should set pointer variables to NULL when you're done with them. This will prevent them from erroneously being deleted again.

Building C++ Applications

Code Organization


Strings and Text

Dates and Times

Managing Data with Containers



Exceptions and Safety

Streams and Files

Science and Mathematics






C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241 © 2008-2020.
If you may any questions please contact us: