C++ delete [] 对象导致崩溃

C++ delete [] object causes crash

我做了一个对象的动态数组。当我调用 delete[] 时,程序崩溃并停止响应。但它有奇怪的行为:调用所有析构函数并崩溃。看看这段代码和输出。所有数组的所有内存都已分配。

//main file
#include "myobject.h"

int size;
myObject *foo;

//some operations to estimate size

foo = new myObject[size];

//some operations with myObject

std::cout<<"size: "<<size<<"\n";
std::cout<<"Deleting object\n";

size=0;
delete [] foo;

下一个文件:

//myobject.h

class myObject
{
    public:
    int number;

    Object1 ob1[64]
    Object2 *ob2;

    myObject(){ };
    ~myObject()
    {
        std::cout<<"delete "<<number<<"\n";

        delete [] ob1;
        delete [] ob2;
    };
}

并且输出:

size: 11

Deleting object

delete 10

delete 9

delete 8

delete 7

delete 6

delete 5

delete 4

delete 3

delete 2

delete 1

delete 0

然后它崩溃并停止响应。

您只能对 new[] 返回的指针调用 delete[],并且您必须只调用一次。这同样适用于 deletenew

特别是,您不能 delete[] obj1 因为它是内置数组,而不是指针,并且 obj2 仅当它指向用 new[] 分配的未释放内存时。

delete [] ob1;

你没有new obj1;它是包含在对象中的数组。删除未分配给 new 的任何内容会产生未定义的行为,这很可能是崩溃。

如果你要像这样玩转指针,那么你需要了解 Rule of Three to avoid the next deathtrap you'll encounter. Then learn about RAII and smart pointers,并忘掉这些危险的废话。