提问人:Hardik 提问时间:9/30/2023 更新时间:9/30/2023 访问量:79
为什么派生类重载删除运算符被调用?
Why derived class overloaded delete operator called?
问:
#include <iostream>
using namespace std;
struct A
{
virtual ~A() { cout << "~A ";};
void operator delete(void* p)
{
cout << "A :: operator delete" << endl;
}
void operator delete[](void* p)
{
cout << "A :: operator delete[]" << endl;
}
};
struct B : A
{
~B(){ cout << "~B ";}
void operator delete(void* p)
{
cout << "B :: operator delete" << endl;
}
void operator delete[](void* p)
{
cout << "B :: operator delete[]" << endl;
}
};
int main()
{
A* ptr1 = new B;
A* ptr2 = new B[2];
delete ptr1;
delete [] ptr2;
}
输出:
~B ~A B :: operator delete
~B ~A ~B ~A A :: operator delete[]
删除基类指针 ptr1 时,将调用派生类删除运算符方法,但是在删除 ptr2(保存派生类数组的动态内存位置)时,将使用基类删除运算符方法。谁能解释这种行为?
答: 暂无答案
评论
~B ~A B :: operator delete
~B ~A ~B ~A B :: operator delete[]
B
A