hi everybody im trying to delete void pointer from vector, the program crash in the delete. thank you very much!
template <class T> class tArray_t : public vpArr_t {
virtual ~tArray_t() {
for (vector<void*>::iterator it = array.begin() ; it != array.end(); )
{
vector<void*>::iterator nextElement = it+1;
delete *it; // here is the crash
it = nextElement;
}
};
Deleting void
pointers is undefined . You are getting exactly what you have asked for.
Use vector<T*>
instead of vector<void*>
. If you eg have vector<void*>
inherited from your base class, you have to cast the pointer to T*
before deleting it.
delete static_cast<T*>(*it);
You may also want to save you some work and use boost::ptr_vector
.
Compiler know how many bytes to be deleted with a typed pointer. Think of it this way, a void * pointer doesn't have any information about the memory it pointing to, nobody knows how to delete a pointer like this. To the minimum, you don't know what size needs to be deleted, and no information about which destructor to call.
Class A;
A * p = new A();
delete p;
When delete p is executed, compiler knows A destrcutor needs to be called, and the size of memory needs to be cleaned up is sizeof(A). A void * pointer is missing all this information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.