Vectors of Pointers

vector <someObject *> vb;

vb.push_back(new someObject ());
vb.push_back(new someObject ());
vb.push_back(new someObject ());
vb.push_back(new someObject ());
vb.push_back(new someObject ());

vb.clear

Hmm... Looks to me that something must call delete for every pointers stored in vb first.

Part of me says that there are ways to automatically do that every time we do vb.clear or when vb is destroyed.

But vector can contain something besides pointers. So what am I missing?
May be you need something like http://www.boost.org/doc/libs/1_42_0/libs/ptr_container/doc/tutorial.html

As you've mentioned above, the vector container is not responsible for the memory you've allocated. It is you, who responsible for the memory allocation as well as deallocation.

However, sometimes it is more convenient for the container to collect garbage. The boost provides you with special pointer containers allowing for implicit deallocation.

upd
I suppose, that it is also possible to utilize smart pointers with a safe coping policy like reference count pointers.
Last edited on
How would Stroustrop do it?
In his book Stroustrop says that most vector should be vector of containers. I wonder why he didn't provide any sample how to delete all those pointers
As far as I know the STL containers have been designed as object containers. There are some rules:

i) The object can be copied without any side effect and the copy has to be equivalent to the original object.

ii) The object can be copied with operator= or without any side effect referenced by operator=.

iii) The object can be destroyed by calling it's destructor.


STL containers are templates, theoretically they can be instanced for any type. Still, practically they can be used only with objects that obey the rules stated above.

You can gain more information in book: The C++ Standard Library by Nicolai M. Josuttis
http://www.amazon.com/Standard-Library-Tutorial-Reference/dp/0201379260

STL containers haven't been designed to handle with pointers to the dynamic memory in automatic way.

What's wrong with boost pointer containers? Why don't you want to utilize them?
Last edited on
Because it's not standard. Well, they're good. I am just thinking if there is something standard library provide.

I do see that boost is very good.

Who is boost anyway?
http://www.boost.org/

Go ahead and use their libraries. A bunch of them are going to be added to the next standard anyway.
well i have not used such a thing but anyway you can create an interface containing a vector and u can have the destructor of the interface to deal with deallocation of all the objects in the vector.

seems fine right?
ur comments
Topic archived. No new replies allowed.