c – 在重载的运算符删除函数中是否隐式调用析构函数?

前端之家收集整理的这篇文章主要介绍了c – 在重载的运算符删除函数中是否隐式调用析构函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有类Item,它定义了自己的operator new和operator delete,如下所示:
class Item
{
public:
    Item(const std::string &s):msg(s)
    {
        std::cout<<"Ctor: "<<msg<<std::endl;
    }
    static void* operator new(size_t size,int ID,const std::string &extra)
    {
        std::cout<<"My Operator New. ID/extra: "<<ID<<"/"<<extra<<std::endl;
        return ::operator new(size);
    }
    static void operator delete(void* p)
    {
        std::cout<<"My Operator Delete"<<std::endl;
        return;
    }
    ~Item()
    {
        std::cout<<"Destructor: "<<msg<<std::endl;
    }
    void Print()
    {
        std::cout<<"Item::msg: "<<msg<<std::endl;
    }
private:
    std::string msg;
};

我使用placement new创建了这种类型的对象,然后删除如下:

int main()
{
    Item *pI=new(1,"haha")Item("AC Milan");
    std::cout<<"before delete"<<std::endl;
    delete pI;
    std::cout<<"after delete"<<std::endl;
    return 0;
}

输出是:

My Operator New. ID/extra: 1/haha
Ctor: AC Milan
before delete
Destructor: AC Milan
My Operator Delete
after delete

正如您所看到的,删除pI调用我自己的删除功能,除了输出日志之外没有任何操作.但是,从输出中,Item的析构函数在delete pI中调用,而pI在我自己的delete函数中没有被调用.

那么在这种情况下,析构函数会在重载删除函数中隐式调用吗?

解决方法

So in this case,destructor would be called implicitly in a overloaded delete function?

是.对于delete expression,(1)首先调用析构函数,然后(2)调用apporiate operator delete;在此阶段将执行名称查找和重载解析.

If expression is not a null pointer,the delete expression invokes the destructor (if any) for the object that’s being destroyed,or for every element of the array being destroyed (proceeding from the last element to the first element of the array).

After that,unless the matching new-expression was combined with another new-expression (since C++14) the delete expression invokes the deallocation function,either operator delete (for the first version of the expression) or operator delete[] (for the second version of the expression).

猜你在找的C&C++相关文章