尝试使用以下函数在 C++ 中动态实现数组。
我不确定是否需要删除 newArray,但现在它给出了 memleak。
void DynamicArray::push_back(Element e)
{
if (arraySize == arrayCapacity) // Resizing is necessary
{
// Update private variables
if (arrayCapacity == 0)
{
arrayCapacity += 2;
}
else
{
arrayCapacity *= 2;
}
Element* newArray = new Element[arrayCapacity]; // Make a new array
for (int i = 0; i < arraySize; i++)
{
newArray[i] = dynamicArray[i]; // Copy over old data
}
delete [] dynamicArray; // Remove the old array (prevent memory leak)
dynamicArray = nullptr;
dynamicArray = newArray;
newArray = nullptr;
delete [] newArray;
}
if (arraySize < arrayCapacity) // No resizing needed
{
dynamicArray[arraySize] = e; // With x items are in the array, the new item has an index of x
arraySize += 1;
}
}
似乎会导致内存泄漏