gpt4 book ai didi

c++ - 在成员函数中使用 'delete this' 后,我可以访问其他成员函数。为什么?

转载 作者:太空狗 更新时间:2023-10-29 23:36:52 27 4
gpt4 key购买 nike

我刚刚写了一个示例程序来查看delete this

的行为
class A
{
~A() {cout << "In destructor \n ";}
public:
int a;
A() {cout << "In constructor \n ";}

void fun()
{
cout << "In fun \n";
delete this;
cout << this->a << "\n"; // output is 0
this->fun_2(); // how m able to call fun_2, if delete this is called first ??
}

void fun_2()
{
cout << "In fun_2 \n";
}

main()
{
A *ptr = new A;
ptr->a = 100;
ptr->fun(); //delete this will be executed here
ptr->fun_2(); //how m able to execute fun_2 when this pointer is deleted ??
cout<< ptr->a << "\n"; //prints 0
return 0;
}

> Output
In constructor
In fun
In destructor
0
In fun 2
In fun 2
0

问题

  1. 在 fun() 中执行delete this 后,如何使用 fun() 中的 this 指针访问 func_2() ??
  2. 现在主要是如何在删除此指针时执行 obj->fun_2 ??
  3. 如果我在终止此对象后能够访问函数成员,那么为什么数据成员会变成零“0”??

m 使用 linux ubuntu 和 g++ 编译器

最佳答案

  1. 您看到的是未定义的行为:它可能会工作,也可能会崩溃。
  2. 指针指向已删除的实例 - 它是一个悬挂指针。
  3. 这也是未定义的行为:您可能会看到零值或垃圾值。

Eric Lipperthis answer 中提供了一个非常好的“旅馆房间抽屉里的书”类比关于函数返回后指向局部变量的指针的问题,在这里同样适用。

关于c++ - 在成员函数中使用 'delete this' 后,我可以访问其他成员函数。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11887651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com