简体   繁体   English

无法从C ++中的向量中删除void指针

[英]Cant delete void pointer from vector in c++

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 . 删除void指针是未定义的 You are getting exactly what you have asked for. 您正在得到您所要求的。

Use vector<T*> instead of vector<void*> . 使用vector<T*>代替vector<void*> If you eg have vector<void*> inherited from your base class, you have to cast the pointer to T* before deleting it. 例如,如果从基类继承了vector<void*> ,则必须在删除T*之前将其转换为T*

delete static_cast<T*>(*it);

You may also want to save you some work and use boost::ptr_vector . 您可能还需要保存一些工作并使用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. 这样想吧,void *指针没有有关它指向的内存的任何信息,没人知道如何删除这样的指针。 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). 当执行delete p时,编译器知道需要调用一个析构函数,并且需要清除的内存大小为sizeof(A)。 A void * pointer is missing all this information. 无效*指针会丢失所有这些信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM