首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义重载New和Delete运算符

自定义重载New和Delete运算符
EN

Stack Overflow用户
提问于 2021-08-21 11:28:47
回答 1查看 62关注 0票数 0
代码语言:javascript
复制
// Global new and delete operator
void * operator new(size_t size)
{
   cout<< "Overloading new operator with size: " << size << endl;
   void * p = malloc(size); 
   return p;
}
void operator delete(void * p)
{
   cout<< "Overloading delete operator " << endl;
   free(p);
}

class Details
{
    int marks;
    int rollno;
public:
    Details( int marks, int rollno) : marks(marks), rollno(rollno) 
    { 
         cout << "Details Constructor called" << endl;
    }
    void display()
    {
        cout<< "Marks:" << marks << endl;
        cout<< "rollno:" << rollno << endl;
    }
    ~Details() {  cout << "Details Destructor called" << endl;}
};
class student
{
    string name;
    int age;
    Details* d;
public:
    student()
    {
        cout<< "Constructor is called\n" ;
    }
    student(string name, int age, int marks, int rollno) : name{name},age{age} 
    {
        cout << " Student Constructor called" << endl;
        d = new Details{marks, rollno};
    }
    void display()
    {
        cout<< "Name:" << name << endl;
        cout<< "Age:" << age << endl;
        d->display();
    }
    ~student() { cout << " Student Destructor called" << endl; delete d;}   
};
// Driver function
int main()
{
    student * p = new student("Yash", 24 , 5, 1); 
    p->display();
    delete p;
}

输出:

代码语言:javascript
复制
Overloading new operator with size: 29
Overloading new operator with size: 24
Student Constructor called
Overloading new operator with size: 8
Details Constructor called
Name:Yash
Age:24
Marks:5
rollno:1
Student Destructor called
Details Destructor called
Overloading delete operator 
Overloading delete operator 
Overloading delete operator

我预计new和delete运算符函数会被调用2次(针对学生和详细信息)。但是程序的输出显示new和delete操作符函数被调用了3次。为什么?

EN

回答 1

Stack Overflow用户

发布于 2021-08-21 12:38:02

我可能错了,但我认为有另一个代码调用new和delete,从一个包含的库中删除

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68872598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档