问题描述
我目前正在用C ++创建向量类,并且正在尝试一些东西。我不确定是否可以做到这一点而不会导致内存泄漏或遗留内存并且无法正确删除它。我已经评论了我有疑问的代码行。任何帮助将不胜感激,谢谢您!
void remove(unsigned int toRemove)
{
T* tmp = new T[maxsize]; // T is the datatype of the vector
int x = 0;
for (int i = 0; i < size; i++)
{
if (i != toRemove)
{
tmp[x] = array[i]; // does this line cause memory leak ?
}
else
{
x--;
}
x++;
}
delete[] array; // is there anything else I need to delete?
array = tmp;
size--;
}
解决方法
我没有重新分配它,而是这样做了,它工作得更好并且得到了更好的优化。
void remove(unsigned int toRemove)
{
unsigned int x = 0;
for (unsigned int i = 0; i < size; i++)
{
if (i != toRemove)
{
array[x] = array[i]; // shifts the elements backwards
}
else
{
x--;
}
x++;
}
size--;
}