So I'm looking to implement a vector that contains pointers to objects. I've heard that there can be some problems with doing this. In particular, I've been warned to always delete the pointers before removing them from the vector. Are there any other precautions I should take before jumping into this? Thanks in advance!
template <typename T>
struct vec_of_pint: public vector <T*>
{
typedeftypename vector <T*> ::iterator iterator;
typedeftypename vector <T*> ::const_iterator const_iterator;
// Destroying my object automatically frees all its references
virtual ~vec_of_pint()
{
clear();
}
template <typename IteratorType>
IteratorType erase( IteratorType position )
{
delete *position;
return vector <T*> ::erase( position );
}
void resize( size_type n, T* value = T*() )
{
vector <T*> ::resize( n, 0 );
}
void assign( size_type n, const (T*)& value )
{
clear();
vector <T*> ::assign( n, value );
}
};
I think that gets everything to delete properly.
Oh, if T is a pointer to an array of something, you'll have to change delete to delete[].
Hope this helps.
[edit]
Please remember that this is just a hack to do one thing. Don't derive/inherit from it. Don't assume it will solve all kinds of problems. Don't assume that this is a complete class that will do everything you want.
It is just a small, stupid, simple example. Modify it. Play with it. Fix it. Unfix it. Don't use it in critical systems (without extreme testing). Etc.
Whoa, be careful with that. Someday someone will use your vec_of_point polymorphically with std::vector, and some other day someone will add a data member to vec_of_point, and then everyone is screwed.
Furthermore, typedef vector <T*> ::const_iterator const_iterator;
won't work, it should be typedeftypename vector <T*> ::const_iterator const_iterator;
And, last but not least, a stl container has some more requirements then are met here: typedefs of the reference, const_reference, pointer, const_pointer, size_type, difference_type and value_type.
Perhaps the usage of another smartpointer type would be better, e.g. std::tr1::shared_ptr.
Yeah, C++ really does give one the rope to hang oneself and every programmer coming after one ;-).
See what can happen to an experienced programmer. So be careful with features new for you - "treat them like a loaded automatic weapon in a crowded room" (H. Sutter).