C++ 自定义运算符中的 Delete 与 Delete[](不同于常见的 delete 与 delete[] 问题)

Delete vs Delete[] in a custom operator in C++ (different than common delete vs delete[] questions)

我定义了一个名为 MyNewDeleteAllocator 的 class,并为 class 定义了自定义的新建和删除运算符。此代码没有任何错误,并且运行良好。但是,我对代码的第 29 行有疑问。似乎将 "delete[]" 更改为 "delete" 并没有改变我的代码结果中的任何内容。

我知道 delete(由 "new" 分配的单个对象)和 delete[](由 "new[]" 分配的对象数组)之间的区别。

我想知道为什么在第 29 行交换 delete 和 delete[] 不会影响我的结果。

#include <new>
#include <iostream>

using namespace std;

//Allocator class
class MyNewDeleteAllocator {
public:
    MyNewDeleteAllocator() {}
    ~MyNewDeleteAllocator() {}
    static void* operator new (size_t size);
    static void operator delete (void* p);
};

void* MyNewDeleteAllocator::operator new (size_t size) {
    void* p;
    p = malloc(size);
    if (p == NULL) {
        //Throw bad_alloc.
        std::bad_alloc exception;
        throw exception;
    }
    cout << "MyNewDeleteAllocator::operator new called with size_t " << size << endl;
    return p;
}

void MyNewDeleteAllocator::operator delete (void* p) {
    cout << "MyNewDeleteAllocator::operator delete called. " << endl;
    delete[] p; //THIS IS LINE 29
}


int main()
{
    MyNewDeleteAllocator* p = new MyNewDeleteAllocator; //Create MyNewDeleteAllocator object.

    delete p; //Delete MyNewDeleteAllocator object.

    return 0;
}

首先,这不是分配器,或者你的命名约定是错误的。在 C++ 中,分配器为给定类型分配内存,而不是为原始字节分配内存。更多相关信息 - https://en.cppreference.com/w/cpp/memory/allocator

其次,不要混用malloc()/deletenew/free()malloc() 应与 free() 一起使用,new 应与 delete 一起使用,而不是相反。更多相关信息 -

因此,您只需将 malloc() 替换为 new。此外,当您使用 new 时,C++ 将抛出 std::bad_alloc 以防无法分配请求的内存。