下面是我尝试实现的堆栈数据结构的代码片段。
出于某种原因,当我删除 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 [] currentArray;
delete [] newArray;
}
推送有几个问题:
- 您按值传递
value
,这可能很昂贵。您应该通过引用传递。 - 您在
copy()
递增后使用size
,这意味着您将原始内存复制到newArray
的最后一个插槽中.这可能是良性的(T = int + 一点运气)或灾难性的(T = std::string)。 newArray
仅在push()
中需要。应该是局部变量,不是成员变量。- 您每次增长 1,这导致需要 O(n2) 时间来填充。你应该几何增长,这需要一个额外的容量成员变量。
- 您调用
new T[size]
两次。其中一个泄漏。
这是修改后的版本:
class Stack {
public:
…
inline void push(const T& value) {
if (size_ == capacity_) {
capacity_ = capacity_ ? capacity_ * 2 : 1;
T* dest = new T[capacity_];
copy(data_, data_ + size_, dest);
delete [] data_;
data_ = dest;
}
data_[size_++] = value;
}
…
private:
T* data_ = nullptr;
size_t size_ = 0, capacity_ = 0;
};
这绝不是一段可靠的、具有工业强度的代码。它没有解决异常安全、避免复制(除其他事项外,需要额外的重载:push(T&& value)
)和一系列其他细微之处。事实上,我什至没有检查它是否编译!它可能适用于玩具项目,但在现实世界中,您应该简单地使用 std::stack。
关于c++ - 删除数组或释放内存,C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31621803/