尝试删除动态数组时遇到困难

Difficulties while trying to delete a dynamic array

我正在尝试在 class 中创建我自己的数组,其中包含插入、删除等功能。我的数组有 capacity - 最大数组大小,size - 它包含多少个元素,*data - 指向数据的指针。因此,当用户尝试插入一个元素并且数组已满时,capacity 会在我的 resize() 函数中加倍,我会创建一个临时数组 newData[capacity] 复制那里的所有内容,然后删除我的原来data去掉那个内存然后把newData赋值给data。现在我不知道这是否是一个愚蠢的解决方案,但它第一次有效,但当我第二次调整大小时,我得到了奇怪的数字。对于测试,我将起始 capacity 设置为 2。这是 myArray.cpp 文件:

#include <iostream>
#include "myArray.h"

using namespace std;

myArray::myArray()
{
    size = 0;
    capacity = 2;
    data = new int[capacity];
}

void myArray::setData(int n, int idx) {
    data[idx] = n;
}
int myArray::getData(int idx) {
    return data[idx];
}

void myArray::insert(int num) {
    size++;
    if(size > capacity) resize();
    setData(num, size - 1);
}
void myArray::insert(int num, int idx) {
    if(idx == size + 1) insert(num);
    else {
        size++;
        if(size > capacity) resize();
        for(int i = size; i > idx; i--) {
            data[i] = data[i - 1];
            if(i - 1 == idx) data[idx] = num;
        }
    }
}
void myArray::remove(int idx) {
    if(idx == size) {
        delete &data[size];
        size--;
    }
    else {
        for(int i = idx; i < size; i++) {
            data[i] = data[i+1];
        }
        size--;
    }
}
void myArray::resize() {
    cout << "Resizing" << endl;
    capacity *= 2;
    int *newData = new int[capacity];
    for(int i = 0; i < size; i++) {
        newData[i] = data[i];
    }
    delete[] data;
    data = newData;
    delete[] newData;
}

int& myArray::operator[](int idx) {
    return data[idx];
}

void myArray::print() {
    for(int i = 0; i < size; i++) {
        cout << data[i] << " ";
    }
    cout << endl;
}

myArray::~myArray()
{
    //dtor
}

忽略我猜的所有函数,所有的马戏团都必须发生在resize()函数中。 这是头文件

#ifndef MYARRAY_H
#define MYARRAY_H


class myArray
{
    public:
        myArray();
        virtual ~myArray();

        void print();

        void setData(int n, int idx);
        int getData(int idx);

        void insert(int num);
        void insert(int num, int idx);
        void remove(int idx);
        void resize();

        int &operator[](int);

    protected:

    private:
        int size;
        int capacity;
        int *data;
};

#endif // MYARRAY_H

这是我在 main()

中的测试
#include <iostream>
#include "myArray.h"

using namespace std;

int main()
{
    myArray array;
    array.insert(1);
    array.print();
    array.insert(4);
    array.print();
    array.insert(3);
    array.print();
    array.insert(5, 3);
    array.print();
    array.remove(1);
    array.print();
    array.insert(6);
    array.print();
    array[2] = 2;
    array.print();
    array.insert(3, 0);
    array.print();
    return 0;
}

这是我在输出中看到的:

1
1 4
Resizing (everything worked fine)
1 4 3
1 4 3 5
1 3 5
1 3 5 6
1 3 2 6
Resizing (everything is not fine)
3 18248184 18219200 2 6

resize 中,delete[] newData; 语句删除了您刚刚分配的内存,留下 data 作为悬空指针,因为它现在指向已被释放的内存。

解决方案是从 resize 中删除 delete[] newData; 语句。

您还应该向析构函数添加代码以释放您分配的内存。