#include <iostream>
using namespace std;
class BASE
{
public:
virtual ~BASE()
{
cout<<"Base deconstruction"<<endl;
}
};
class CCHILD: public BASE
{
public:
~CCHILD()
{
cout<<"CCHILD deconstruction"<<endl;
}
};
int main(int argc, char const *argv[])
{
BASE *Pbase;
BASE b;
Pbase = &b;
delete Pbase;
cout<<"-----"<<endl;
CCHILD c;
Pbase = &c;
delete Pbase;
return 0;
}
请大神解释,delete为什么提示无效的指针啊
可以简单地认为C++的变量有两类,一类是在程序初始化时已经分配了固定空间的,另一类是由
malloc
动态申请的位于堆空间中的;比如
BASE b
,那么变量b所在位置、所占空间等都是可以确定下来的,属于已经静态分配完成的变量,由编译器安排了其内存地址,是被写死在可执行文件中的;而由
malloc()/new
申请的变量则是动态的,其地址在运行时才被告知,也只有这样的动态分配空间的变量才能被free()/delete
释放空间你的代码想要删除一个被写死在程序中的变量,怎么可能运行成功