delete是C++中的一个运算符,它是和new配合起来使用。我们知道new的实际操作是先分配一块内存,再调用对象的构造函数。而delete恰好和new的操作顺序相反,即先调用析构函数,再释放这块内存。
那现在的问题是如果在类的成员函数中调用delete this,也就是相当于“类对象的自杀”,会发生什么?
这里类的成员函数,大致分成类的普通成员函数和析构函数中对delete的调用。
实践是最好的验证方法,来看代码:
#include <iostream>
using namespace std;
class foo
{
private:
int a;
public:
foo() {
a = 10;
}
~foo() {
a = 0;
}
int test() {
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
delete this;
}
};
int main(int argc, char const *argv[])
{
foo* f = new foo();
f->test();
return 0;
}
上面的代码中,我们是使用new在堆上构造了一个foo对象f,然后调用f的普通成员函数test,在linux下g++的运行结果是

符合我们的预期,没什么问题,这说明了一个结论:在类的成员函数中调用delete this是没有什么问题的。接下来继续看看这个对象的其他地方有没有受到影响。
#include <iostream>
using namespace std;
class foo
{
private:
int a;
public:
foo() {
a = 10;
}
~foo() {
a = 0;
}
void print() {
cout << "test" << endl;
}
int test() {
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
delete this;
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
this->a += 50;
cout << "a的值是 " << a << endl;
}
};
int main(int argc, char const *argv[])
{
foo* f = new foo();
f->test();
return 0;
}
上面的代码中我们在delete之后打印输出a的值和this的地址,运行的结果如下:

分析一下,当调用delete this之后,按照之前所说,首先会调用foo的析构函数,将a的值更改为0,接着将this所指向的内存空间释放。
在我们的运行结果中,我们发现前者是验证了。但是好像这个指针还是可以使用的,并没有认为this指针越界或者野指针。查了一下这个问题,在有的博客中提到是因为操作系统并没有立即就回收这块内存。
接着我尝试了一下不在堆上分配内存,而是一个栈对象。
#include <iostream>
using namespace std;
class foo
{
private:
int a;
public:
foo() {
a = 10;
}
~foo() {
a = 0;
}
void print() {
cout << "test" << endl;
}
int test() {
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
delete this;
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
this->a += 50;
cout << "a的值是 " << a << endl;
}
};
int main(int argc, char const *argv[])
{
foo f;
f.print();
f.test();
return 0;
}
运行结果如下:

出现了错误,报错在free函数的时候发现这个指针异常。原因我认为是在调用delete的时候,会先调用析构函数,再释放内存。而这只是个栈对象,不是堆内存,调用free会报错。可以通过写一个delete 栈指针来验证,会发现同样的错误。
下面考虑在析构函数中调用delete this,会发生什么
#include <iostream>
using namespace std;
class foo
{
private:
int a;
public:
foo() {
a = 10;
}
~foo() {
a = 0;
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
delete this;
cout << "a的值是 " << a << endl;
cout << "this保存的地址是 " << this << endl;
}
};
int main(int argc, char const *argv[])
{
foo* f = new foo();
delete f;
return 0;
}
运行结果如下:

从结果来看是进入了一个死循环。原因其实很简单,在析构函数中调用delete this,那么delete this又会去调用析构函数,这样就形成了一个互相循环的调用。
总结
- 栈对象的普通成员函数中调用delete this,会出现错误指针;
- 堆对象的普通成员函数中调用delete this,并不会出现什么错误(未考虑继承虚函数情况)。而在析构函数中调用delete this,会出现死循环。
本文探讨了在C++中,类的普通成员函数和析构函数中调用`delete this`的影响。实验结果显示,普通成员函数中调用`delete this`不会引发问题,但析构函数中这样做会导致死循环。对于栈对象,`delete this`会导致错误,而堆对象则会在析构后释放内存。
6720

被折叠的 条评论
为什么被折叠?



