全局重载new和delete运算符

问题描述

我试图全局重载new和delete运算符。 代码是:

void * operator new(size_t s)
    {
        cout<<"\nOverloaded new operator with size "<<s<<endl;
        void * ptr=::malloc(s);
        return  ptr;
    }
    void operator delete(void * ptr)
    {
        cout<<"\nOverloaded delete operator\n";
        free(ptr);
    }
class Array
{
    int * arr;
    int n;
public:

    Array(int x=0):n{x}
    {
        cout<<"\nConstructor called\n";
        arr= new int[n];
    }

    ~Array()
    {
        cout<<"\nDestructor called\n";
        delete[]arr;
    }
    void set_data()
    {
        cout<<"\nEnter elements:";
        for(int i=0;i<n;i++)
        {
            cin>>arr[i];
        }

    }
    void show_data()
    {
         for(int i=0;i<n;i++)
            cout<<arr[i]<<" ";
    }


};
int main()
{
    Array * a=new Array{3};
    a->set_data();
    a->show_data();
    delete a;


    return 0;

}

当我尝试使用new创建Array对象时,set_data()函数输出使我感到困惑。在我看来,好像每次将数组元素作为输入时,都会在堆上创建一个对象并立即将其删除。 请解释这种行为 输出

Output for Array of three elements

我也是第一次做这个概念。因此,如果我在理解概念上有误,请帮助我

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)