c++ - 删除数组或释放内存,C++ 错误

标签 c++ memory-management data-structures stack dealloc

下面是我尝试实现的堆栈数据结构的代码片段。

出于某种原因,当我删除 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;
}

推送有几个问题:

  1. 您按值传递 value,这可能很昂贵。您应该通过引用传递。
  2. 您在 copy() 递增后使用 size,这意味着您将原始内存复制到 newArray 的最后一个插槽中.这可能是良性的(T = int + 一点运气)或灾难性的(T = std::string)。
  3. newArray 仅在 push() 中需要。应该是局部变量,不是成员变量。
  4. 您每次增长 1,这导致需要 O(n2) 时间来填充。你应该几何增长,这需要一个额外的容量成员变量。
  5. 您调用 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/

相关文章:

c++: `this == nullptr` 在成员函数中安全吗?

c - 我什么时候应该在 C 中使用 malloc,什么时候不应该?

c# - 我该如何解决我的内存问题

java - java中所有集合背后使用的数据结构

python - 如何在python字典中执行递归

c++ - 如何使用 Zstd 压缩 C++ 字符串?

c++ - 如何使用 std::vector 初始化 boost::random::discrete_distribution?

c++ - 在 C++ 中避免类定义中的循环依赖

c++ - Symbian C++ 的内存管理实践和工具

data-structures - 基本数据结构列表 - 我错过了什么?