为什么析构函数会在这里被调用两次?

hjj*_*200 0 c++ struct destructor

#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
Run Code Online (Sandbox Code Playgroud)

我有这个代码,我试图手动删除结构变量.这样做,我意识到析构函数在这里被调用了两次.为什么会这样?destruct()调用时为什么不删除?

M.M*_*M.M 6

delete this调用导致未定义的行为,这意味着在所有的一切都有可能发生.

delete可能只能用于创建的对象new.


对于具有非平凡析构函数的自动对象(例如你的A1),除非你ABC在范围结束之前在同一个地方创建另一个,否则不可能"尽早销毁它们" .换句话说,您无法"关闭"范围结束时发生的销毁过程.