delete this

一般不要用,用了就要注意一下几点

1. 只能用于 new 申请的对象,不能用于栈上对象

#include <iostream>

class A
{
public:
    void func()
    {
        delete this;
    }
};

int main(int argc, char const *argv[])
{
    A *ptr = new A;
    ptr->func();
    ptr = nullptr;

    A a;
    a.func(); // 这里会挂掉
    getchar();

    return 0;
}

2. delete之后,任何成员都不能再用了

#include <iostream>
class A
{
    int x;

public:
    A() { x = 0; }

    void func()
    {
        delete this;
        std::cout << x; // 未定义行为
    }
};

int main(int argc, char const *argv[])
{
    A *obj = new A;
    obj->func();
    return 0;
}

3. 最好是,不要这样用

posted @ 2022-05-25 23:01  suntus  阅读(75)  评论(0编辑  收藏  举报