删除这个?它有什么作用?

Ron*_*n_s 2 c++ destructor self-destruction delete-operator

鉴于以下内容:

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

输出是:

ctor A
The X value: 5
dtor A
The X value: 5
dtor A
Run Code Online (Sandbox Code Playgroud)

不会delete this;有任何激烈的反响?

sel*_*tze 5

在这种情况下(您没有通过new分配A对象),您正在调用未定义的行为.未定义的行为通常是非常非常糟糕的事情.基本上,任何事情都可能发生.

可以编写代码"删除这个;" 不过会没事的.但我不记得曾经这样做过.尽量避免它.尝试通过将此职责委托给其他对象(例如,智能指针)来避免手动调用删除(无论您是否使用了新的).