【发布时间】:2014-04-24 20:16:42
【问题描述】:
大家好,我试图从向量中删除 void 指针,程序在删除时崩溃。 非常感谢!
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;
}
};
【问题讨论】:
-
如果它在
delete操作上崩溃,这意味着你在向量中有一个无效的指针;或者至少是一个没有用new分配的指针。 -
C++ 标准第 5.3.5/3 节:
[...] an object cannot be deleted using a pointer of type void* because there are no objects of type void. -
@Nik 因为如果
it等于end(),则无法进入循环体。 -
@Chnossos 如果 it==(lastElement) 然后你执行“it+1”怎么办,你不是在这里越过最后一个元素吗?然后尝试删除不是通过代码分配或可能属于其他代码的位置。
-
@Nik 他实际上是在删除
it,而不是nextElement,所以如果它达到了这一点,一切都很好。标准容器确保end()始终过去最后一个元素。