J
junw2000
I use the code below to study delete and destructor.
#include <iostream>
using namespace std;
struct A {
virtual ~A() { cout << "~A()" << endl; }; //LINE1
void operator delete(void* p) {
cout << "A:perator delete" << endl;
free(p);
}
};
struct B : A {
void operator delete(void* p) {
cout << "B:perator delete" << endl; //LINE2
free(p);
}
~B(){ cout << "~B()" << endl; }; //LINE3
};
int main() {
A* ap ;
B *bp = new B;
ap = bp;
delete ap; //LINE4
}
The output of the code is:
~B()
~A()
B:perator delete
I can not understand the output. When LINE4 is executed, LINE1 is
executed, right?
Since ~A() is virtual, LINE3 is called. How can LINE2 be executed?
"delete ap" calls A's destructor. Then B's destructor is called. Can
B's destructor call B's operator delete?
In general, delete invokes destructor, right? Can destructor invoke
delete?
Thanks a lot. I can not find the answer from my C++ books.
Jack
#include <iostream>
using namespace std;
struct A {
virtual ~A() { cout << "~A()" << endl; }; //LINE1
void operator delete(void* p) {
cout << "A:perator delete" << endl;
free(p);
}
};
struct B : A {
void operator delete(void* p) {
cout << "B:perator delete" << endl; //LINE2
free(p);
}
~B(){ cout << "~B()" << endl; }; //LINE3
};
int main() {
A* ap ;
B *bp = new B;
ap = bp;
delete ap; //LINE4
}
The output of the code is:
~B()
~A()
B:perator delete
I can not understand the output. When LINE4 is executed, LINE1 is
executed, right?
Since ~A() is virtual, LINE3 is called. How can LINE2 be executed?
"delete ap" calls A's destructor. Then B's destructor is called. Can
B's destructor call B's operator delete?
In general, delete invokes destructor, right? Can destructor invoke
delete?
Thanks a lot. I can not find the answer from my C++ books.
Jack