【发布时间】:2020-12-03 11:55:08
【问题描述】:
我目前正在用 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--;
}
【问题讨论】:
-
maxsize是const吗? -
请提供minimal reproducible example。什么是数组?什么是T?
tmp[x] = array[i];会扔吗? -
我看到的一个问题是
toRemove是unsigned int但您使用int i进行迭代。另一个问题是,如果代码中存在异常,例如array包含非平凡对象并且tmp[x] = array[i];抛出异常,您可能会泄漏。 -
不用说,以临时方式创建自己的矢量类并不能很好地工作。最好获取有关其完成方式的示例并进行研究。
-
旁注:删除元素时调整数据存储的大小是昂贵的。只需将后面的元素移过来以覆盖孔并将大小减小 1。稍后您可能会再次需要内存,所以最好保留它。
标签: c++ arrays memory vector erase