0%

delete this

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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之后,任何成员都不能再用了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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. 最好是,不要这样用