kathy said:
I am using std::vector in my program:
func()
{
std::vector <CMyClass *> vpMyClass;
vpMyClass.push_back(new CMyClass());
vpMyClass.push_back(new CMyClass());
vpMyClass.push_back(new CMyClass());
//???? Required ??????????????//
delete vpMyClass[0];
delete vpMyClass[1];
delete vpMyClass[2];
}
or vector automatically delete all pointer when it is out of the scope?
Vector just knows about the value that it's storing - a binary value of
the size of memory addresses on your system. It doesn't know or care
about what that value actually means. So, yes, if you store pointers to
dynamically allocated memory in a vector, you are responsible for
freeing the memory yourself.
Another perspective: If vectors containing pointers somehow knew to free
dynamically allocated objects before deleting the entries, then the
following code would probably crash your system:
func()
{
std::vector<char*> vec;
vec.push_back("a string");
vec.push_back(new char[100]);
vec.push_back(NULL);
}
The second thing that I push is a pointer to dynamically-allocated
memory that must be freed. The first, however, is a pointer to
statically-allocated memory, and attempting to delete it would result in
undefined behaviour. The third points to nothing at all, although I
think that delete is supposed to handle null pointers.
If you must store pointers to dynamically allocated memory in STL
containers (and there are reasons to do so), then you really should
write your own wrapper class that handles both allocations and deletions
itself, to ensure that no pointers to non-dynamic memory get stored, and
that everything is appropriately deleted. Also, if there's a chance of
an exception being thrown in your code, make sure that exceptions can't
result in memory leaks.
Rennie deGraaf