#include <iostream>
struct ABC{
int A;
ABC(int i = 1) : A(i) {}
~ABC() {
std::cout << A << std::endl;
}
void destruct() {
delete this;
}
};
int main() {
ABC A1(2);
A1.destruct();
return 0;
}
Output:
2
2
我有这段代码,我在其中尝试手动删除结构变量。这样做,我意识到析构函数在这里被调用了两次。为什么会这样?为什么在调用 destruct()
时它没有被删除?
最佳答案
delete this
调用导致 undefined behaviour ,这意味着任何事情都可能发生。
delete
只能用于 new
创建的对象。
对于具有非平凡析构函数的自动对象(例如您的 A1
),除非您还在范围结束前的相同位置。换句话说,您不能“关闭”作用域结束时发生的销毁过程。
关于c++ - 为什么析构函数在这里被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37433495/