C++中delete和delete[]的区别

2021-12-24 00:00:00 memory-management c++ delete-operator

可能的重复:
C++ 中的删除与删除[] 运算符

我写了一个包含两个指针的类,一个是 char* color_ 一个是 vertexesset* vertex_ 其中 vertexesset 是一个我创建的类.在我开始时写的析构函数中

I've written a class that contains two pointers, one is char* color_ and one in vertexesset* vertex_ where vertexesset is a class I created. In the destractor I've written at start

delete [] color_;
delete [] vertex_;

当涉及到析构函数时,它给了我一个分段错误.

When It came to the destructor it gave me a segmentation fault.

然后我将析构函数改为:

Then I changed the destructor to:

delete [] color_;
delete vertex_;

现在它工作正常.两者有什么区别?

And now it works fine. What is the difference between the two?

推荐答案

当你new一个数组类型时,你delete [],然后delete代码> 当你没有.示例:

You delete [] when you newed an array type, and delete when you didn't. Examples:

typedef int int_array[10];

int* a = new int;
int* b = new int[10];
int* c = new int_array;

delete a;
delete[] b;
delete[] c; // this is a must! even if the new-line didn't use [].

相关文章