调用delete []会破坏我的C++程序

gre*_*ora 1 c++ memory arrays allocation dynamic

更新:感谢您的快速回复.我似乎发布了旧版本的代码.除参数化构造函数外,一切都保持不变.您可以看到代码中存在一些缺陷,但请记住,我还没有完全完成此操作.目前我更担心阵列,因为这是昨天推出的一个新概念.我尝试了几种不同的东西,并研究了几个小时.大多数响应都说只使用向量类,但这是为了帮助我们理解内存分配和动态数组的功课.目前这是我的.cpp和.h文件给我带来了问题.每次触发删除(或清除功能)操作时,都会发生错误,表明blahblah.exe已触发断点.

MyVector.h

#pragma once

class MyVector
{
private:
    int arraySize; 
    int arrayCapacity;
    int* theData;
    void grow();

public:
    MyVector();
    MyVector(int n);
    int size() const;
    int capacity() const;
    void clear();
    void push_back(int n);
    int& at(int n);
    ~MyVector();
};
Run Code Online (Sandbox Code Playgroud)

MyVector.cpp

   #include "MyVector.h"
    #include <iostream>
    using namespace std;

    MyVector::MyVector()
    {
    arraySize = 0;
    arrayCapacity = 0; 
    theData = new int[0];
    }
    MyVector::MyVector(int capacityIn)
    {
    theData = new int [capacityIn];
    arraySize = 0;
    arrayCapacity = 0;
    }
    int MyVector::size() const
    {
    return arraySize;
    }
    int MyVector::capacity() const
    {
    return arrayCapacity;
    }
    void MyVector::clear()
    {
        delete [] theData;
        theData = nullptr;
    }
    void MyVector::push_back(int n)
    {
        if (arrayCapacity==0)
        {
        arrayCapacity++;
        MyVector(arrayCapacity);
    }
    if (arraySize == arrayCapacity)
    {
        grow();
        MyVector(arrayCapacity);
    }
    theData[arraySize] = n;
    arraySize++;
}
int& MyVector::at(int index)
{
    if (index >= 0 && index<arraySize)
    {
        return (theData[index]);
    }
    else
    {
        throw index;
    }
}
void MyVector::grow()
{
    arrayCapacity = arrayCapacity + arrayCapacity;
}

MyVector::~MyVector()
{
    if (theData != nullptr)
    {
        clear();
    }
}
Run Code Online (Sandbox Code Playgroud)

ten*_*our 5

您已经看到了许多问题:

  1. 你不应该像这样明确地调用构造函数.它不符合你的想法.将分配放在真实的成员函数中.
  2. 每次"增长"数组时,只需分配new,导致泄漏,因为前一个指针未被删除.
  3. 你要问的主要问题是:你甚至没有存储你在构造函数中分配的指针.更改int* theData = new int [capacityIn];theData = new int [capacityIn];.例如,您在第一个构造函数中正确地执行了此操作.
  4. 您没有初始化arraySizearrayCapacity在您的第二个构造函数(MyVector(int))中.

吹毛求疵:

  1. nullptr删除前无需检查.
  2. 没有必要new int[0].你永远不应该访问内存,所以只需将其初始化为nullptr.