本文介绍了写入析构函数时,删除NULL指针不会调用重载的删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Widget
{
    public:
        Widget() {
            cout<<"~Widget()"<<endl;
        }
        ~Widget() {
            cout<<"~Widget()"<<endl;
        }

    void* operator new(size_t sz) throw(bad_alloc) {
        cout<<"operator new"<<endl;
        throw bad_alloc();
    }

    void operator delete(void *v) {
        cout<<"operator delete"<<endl;
    }

};

int main()
{
    Widget* w = 0;
    try {
        w = new Widget();
    }
    catch(bad_alloc) {
        cout<<"Out of Memory"<<endl;
    }

    delete w;
    getch();
    return 1;
}

在此代码中,当析构函数在其中时,delete w不会调用重载的delete运算符.如果省略析构函数,则调用重载的delete.为什么会这样?

In this code, delete w does not call the overloaded delete operator when the destructor is there. If the destructor is omitted, the overloaded delete is called. Why is this so?

写入〜Widget()时的输出

未编写〜Widget()时的输出

推荐答案

我记得前一段时间在comp.lang.c ++.moderated中,对运算符进行了类似的删除.我现在找不到它,但是答案表明是这样的..

I remember something similar on operator delete a while ago in comp.lang.c++.moderated. I cannot find it now, but the answer stated something like this ..

詹姆斯·坎泽(James Kanze)专门说:

我记得这个becoz有时也有类似的问题,并将答案保存在.txt文件中.

I remember this becoz i had a similar prob sometime back and had preserved the answer in a .txt file.

UPDATE-1:

哦,我在此处找到了它.另请阅读此链接缺陷报告.因此,答案是 未指定 . 5.3.5/7 一章.

Oh i found it here.Also read this link defect report.So, the answer is Unspecified. Chapter 5.3.5/7.

这篇关于写入析构函数时,删除NULL指针不会调用重载的删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:37