【发布时间】:2021-12-05 23:02:29
【问题描述】:
我正在研究动态数组。数组类相关部分代码:
#pragma once
#include <iostream>
template <class T>
class Darray
{
private:
T* dataArray;
int a_size = 0;
int a_capacity = 0;
double expandFactor = 1.5;
private:
void memLoc(int n_capacity)
{
T* newArray = new T[n_capacity];
for (int i = 0; i < a_size; i++)
{
newArray[i] = dataArray[i];
}
dataArray = newArray;
delete[] newArray; //<-- **************problem occurs here**************
a_capacity = n_capacity;
}
public:
Darray()
{
T* dataArray = new T[a_size];
memLoc(2);
}
void addLast(T data)
{
if (a_size < a_capacity)
{
dataArray[a_size] = data;
a_size++;
}
else
{
memLoc(a_capacity * expandFactor);
dataArray[a_size] = data;
a_size++;
}
}
当我运行代码而不删除 newArray 我得到预期的结果:
Values
Index 0: 10
Index 1: 9
Index 2: 8
Index 3: 7
Index 4: 6
Index 5: 5
Index 6: 4
Index 7: 3
Index 8: 2
Index 9: 1
这是我的问题!当我删除 newArray(在代码中标记)时,我的结果远非准确:
Values
Index 0: -572662307
Index 1: -572662307
Index 2: 100663302
Index 3: 31812
Index 4: 17648624
Index 5: 17649832
Index 6: -572662307
Index 7: -572662307
Index 8: -572662307
Index 9: -572662307
我不知道为什么会这样,因为乍一看一切似乎都是正确的。任何建议或提示将不胜感激。我希望有人能够提供帮助;)
【问题讨论】:
-
您不应该删除旧数组,而不是刚刚分配的新数组吗?
-
恕我直言,您最好花时间了解
std::vector,而不是编写自己的动态数组类。 -
@Frank 我使用 dataArray 作为类的属性,因此我创建了更大尺寸的新数组,复制它,然后将值传递给 dataArray。在代码中:dataArray = newArray。此时 newArray 在内存中未使用,因此我想删除它。我错过了什么吗?因为我不知道为什么会这样。如果我错了,请纠正我。
-
@ThomasMatthews 我已经看到了,这要容易得多,但这是拼贴的任务,他们希望我们这样做:/
-
@Swagelele 这不是指针的工作方式。
dataArray和newArray不是数组本身,它们是数组的指针。所以在dataArray = newArray之后,它们都指向同一个数组:新的。