我正在尝试删除子类的对象。尽管我使用了虚拟析构函数,但仍收到错误消息:
malloc: *** error for object 0x7ffee08bab50: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
我的代码是:
#include <iostream>
using namespace std;
class Animal{
protected:
int age;
public:
Animal(){
age = 0;
cout << "ctor Animal" << endl;
}
virtual ~Animal(){
cout << "dtor Animal" << endl;
}
};
class Mammal : public Animal{
public:
Mammal(){
age = 0;
cout << "ctor Mammal" << endl;
}
~Mammal(){
cout << "dtor Mammal" << endl;
}
};
int main(){
Mammal *dog = new Mammal();
delete &dog;
}
如果有人帮助我,我将非常感激!
@songyuanyao是正确的:delete dog
而不是delete &dog
。您分配了地址存储在中的内存dog
。&dog
是该地址的存储地址,可能在堆栈上。所以&dog
是一个Mammal **
,你没有new
,但是这是不是在堆栈上的编译器自动创建。既然没有new
,那你就做不到delete
。
顺便说一句,如果您想查看虚拟析构函数的效果,请使用Animal *dog = new Mammal();
。由于您声明dog
为aMammal
并将其创建为a Mammal
,因此无论其是否是虚拟的,都会调用正确的析构函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句