【发布时间】:2011-11-05 10:11:22
【问题描述】:
鉴于以下情况:
#include <iostream>
using namespace std;
class A
{
public:
void func() {delete this;}
A() : x(5) {cout << "ctor A" << endl;}
~A() {cout << "dtor A" << endl;}
int x;
};
int main() {
A a;
cout << "The X value: " << a.x << endl;
a.func(); // calling 'delete this' ->going to the dtor #1
cout << "The X value: " << a.x << endl;
return 0;
}
输出是:
ctor A
The X value: 5
dtor A
The X value: 5
dtor A
delete this; 有什么严重的影响吗?
【问题讨论】:
-
试图删除尚未通过 new 分配的内容:错误。删除后尝试访问某些内容:错误。
-
我同意你的观点,我只想表明,即使在第一次删除调用之后,该对象仍然保留“x”的值……只是对我来说有点奇怪。
-
“x”值可能是 5,也可能不是。并且应用程序可能会或可能不会崩溃。看这个经典的解释:stackoverflow.com/questions/6441218/…
-
我很好奇:是什么促使你尝试这个?
-
我也很好奇。我知道这是一个禁忌!只是想知道为什么。
标签: c++ destructor delete-operator self-destruction