// 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;
}输出:
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次。为什么?
发布于 2021-08-21 12:38:02
我可能错了,但我认为有另一个代码调用new和delete,从一个包含的库中删除
https://stackoverflow.com/questions/68872598
复制相似问题