腾讯笔试题:
#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;
}
运行结果是编译通过,a是随机数;
Test mytest;
cout<<mytest.a<<endl;
return 0;
mytest是局部对象,内存在栈上分配,delete this试图释放栈上的内存,因此会报错。