【发布时间】:2015-10-15 19:00:03
【问题描述】:
下面是我正在尝试实现的堆栈数据结构的代码的 sn-p。
由于某种原因,当我删除 currentArray 时,newArray 也被删除了,因为下面的代码给了我一个运行时错误,其中 newArray 和 currentArray 的内容是垃圾值。
我不确定为什么会这样。
非常感谢任何关于我为什么会遇到这个错误的见解,以及我下面的push() 实现是否从基本角度来看是正确的。
// Destructor
~Stack()
{
if ((size > 0) && (currentArray) != NULL && (newArray != NULL))
{
delete[] currentArray;
delete[] newArray;
}
}
inline void push(T value)
{
if (isEmpty())
{
// Stack size is increased by 1
size++;
currentArray = new T[size];
currentArray[size - 1] = value;
}
else
{
// Stack size is increased by 1
size++;
// Create the new array
newArray = new T[size];
// Copy the contents of the old array into the new array
copy(currentArray, currentArray + size, newArray);
// Push the new value on to the new array
newArray[size - 1] = value;
// Copy the new array into the current
currentArray = new T[size];
currentArray = newArray;
}
}
【问题讨论】:
-
首先,请发布一个完整但很小的程序来演示错误。其次,你的
Stack的析构函数看起来很奇怪——为什么你需要所有这些条件来delete[]内存?只需delete[]即可,无需所有这些条件。 -
另外,你的
push函数中的delete[ ]在哪里摆脱旧记忆?如果currentArray已分配,则您已创建内存泄漏。这就是为什么我们需要查看所有内容,而不是 sn-p。我敢打赌,你在这门课上遇到的麻烦要早得多,而且是你没有向我们展示的代码。 -
优化说明。当增加堆栈的大小时,不要只是将大小增加一,因为每次添加时复制堆栈所花费的时间会影响您的性能。将大小增加一些合理的数字。甚至可能翻倍。
标签: c++ memory-management data-structures stack dealloc