需要分情况讨论:以下环境为Ubuntu20.04 g++ 9.4.0
-
当数据是基本数据类型时,由于没有析构函数,所以系统没有必要记录数组大小。所以new[]后的指针就是实际申请内存大小,所以delete与delete[]没有区别,以下代码是不会抛出申请与释放指针不一致异常
#include <iostream> int main() { int * a = new int[10] ; delete a; getchar(); return 0; }
-
当数据为自定义数据类型时,由于需要挨个调用析构函数,所以在mallco时会多申请一个8位,来存储数组大小,导致new返回的指针并不是原始指针,而是在mallco的指针移动8位后的指针。
-
当delete,到operator delete执行时就是new返回的指针,而不是真实指针。所以释放会抛出申请与释放指针不一致异常
#include <iostream> using namespace std; class A { public: A() { } ~A() { std::cout << "A" << std::endl; } static void operator delete[](void* ptr) { std::cout << "custom delete for PTR " << ptr << '\n'; ::operator delete[](ptr); } static void operator delete(void* ptr, std:: size_t sz ) { std::cout << "custom delete for PTR " << ptr << '\n'; ::operator delete(ptr); } }; int main() { A * a = new A[10] ; std::cout << a << std::endl; delete a; getchar(); return 0; }
0x558f7965aeb8
A
custom delete for PTR 0x558f7965aeb8
munmap_chunk(): invalid pointer
Aborted (core dumped) -
当**delete[]**时,调用operator delete[]时执行的指针就是new返回的指针移动8位后的指针,正好是mallco出来的指针,这样就不会异常
#include <iostream> using namespace std; class A { public: A() { } ~A() { std::cout << "A" << std::endl; } static void operator delete[](void* ptr) { std::cout << "custom delete for PTR " << ptr << '\n'; ::operator delete[](ptr); } static void operator delete(void* ptr, std:: size_t sz ) { std::cout << "custom delete for PTR " << ptr << '\n'; ::operator delete(ptr); } }; int main() { A * a = new A[10] ; std::cout << a << std::endl; delete[] a; getchar(); return 0; }
0x560989727eb8
A
A
A
A
A
A
A
A
A
A
custom delete for PTR 0x560989727eb0
-