野指针问题是困扰C++程序员的杀手之一,本文分析了一个野指针的案例。
#include 'stdafx.h'
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class Test
{
public:
Test()
{
a = 9;
delete this;
}
~Test()
{
cout<<'destructor called!'<<endl;
}
int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
Test *mytest = new Test(); //mytest的值和this指针的值是一样一样的
cout<<mytest->a<<endl;
return 0;
}
请问运行结果如何?
常见的回答,程序会报错,通不过编译。或者说编译通过,运行时报错,因为居然Test类的构造函数删除了this指针,相当于