可能重复:
C++:删除这个?
面向对象自杀或删除此;
我想知道下面的代码是否安全运行:
#include <iostream>
using namespace std;
class A
{
public:
A() {
cout << "Constructor" << endl;
}
~A() {
cout << "Destructor" << endl;
}
void deleteMe() {
delete this;
cout << "I was deleted" << endl;
}
};
int main()
{
A *a = new A();
a->deleteMe();
cout << "Exit ...";
return 0;
}
输出是:
Constructor
Destructor
I was deleted
Exit ...
并且程序正常退出,但是这里有一些内存访问暴力吗?