在 C++ 中重载 delete [] 运算符

overloading delete [] operator with throw in c++

本文关键字:运算符 delete 重载 C++      更新时间:2023-10-16

根据代码,它应该执行 catch 块,但为什么它不执行

如何在重载删除运算符中测试 else 运算符

提前致谢

#include<iostream>
#include<stdlib.h>
using namespace std;
void operator delete[](void *p) throw(int)
{
    if (p)
    {
        cout << "address of p is" << p << endl;
        free(p);
        cout << "in deleten" << endl;
    }
    else
    {
        cout << "in throw n";
        throw 5;
    }
}
int main()
{
    try
    {
        int *a = new int[20];
        a = NULL;
        delete[] a;
    }
    catch (...)
    {
        cout << "in catch" << endl;
    }
}
运算符

重载函数中的 *p 接受地址。使用 & after delete 语句调用时发送地址。在此示例中...

#include<iostream>
#include<stdlib.h>
using namespace std;
void operator delete[](void *p = NULL) throw(int)
{
    if (p)
    {
        cout << "address of p is" << p << endl;
        free(p);
        cout << "in deleten" << endl;
    }
    else
    {
        cout << "in throw n";
        throw 5;
    }
}
int main()
{
    try
    {
        int *a = new int[20];
        a = NULL;
        delete[] &a;
    }
    catch (...)
    {
        cout << "in catch" << endl;
    }
}