在成员函数中使用“删除此”后,我可以访问其他成员函数。为什么? [英] After using 'delete this' in a member function I am able to access other member functions. Why?

查看:162
本文介绍了在成员函数中使用“删除此”后,我可以访问其他成员函数。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚写了一个示例程序来查看删除此行为

I just wrote a sample program to see the behaviour of 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()中执行删除此后,我如何使用fun()中的此指针访问func_2()?


  2. 如果我能够在杀死此对象后访问函数成员,那么为什么我可以执行 obj-> fun_2 data members are comming zero'0'??

  1. After executing delete this in fun(), how I am able to access func_2() with this pointer in fun() ??
  2. Now in main how I am able to do obj->fun_2 as this pointer is deleted ??
  3. If I am able to access function members after killing this object, then why data members are comming zero '0' ??

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

m using linux ubuntu and g++ compiler

推荐答案

让我们比较一下类似的szenario:

Let's compare that to a similar szenario:

A * a = new A();

func(a);

删除a;

func2(a);

A *a= new A();
func(a);
delete a;
func2(a);

在我的示例中,编译器只将指针a传递给func和func2,它不关心它是否指向一个有效的对象。因此,如果你调用func2(a)和func2解引用指针,这是未定义的行为。如果内存释放回操作系统,程序可能会崩溃,程序不能再访问* a。通常,delete保持内存分配,不会将其传回操作系统,因此在删除后访问* a不会给出异常,而只是返回任何值。这可能是* a的以前的值,但它也可以是任何其他值,取决于删除的实现,并且取决于在删除 * a 。 MSVC例如在调试模式下将内存设置为预定义模式,以便在访问释放的内存时可以轻松找到。

In my sample the compiler just passes the pointer a to func and func2, it does not care if it is pointing to a valid object. So if you call func2(a) and func2 dereferences the pointer, this is undefined behaviour. The program might crash if the memory was released back to the operating system and the program cannot access *a anymore. Normally delete keeps the memory allocated, does not pass it back to the operating system, so accessing *a after delete will not give an exception, but just return any value. This might be the previous values of *a, but it might also be any other value depending on the implementation of delete and depending on other calls to new done between delete a and *a. MSVC for example sets the memory to a predefined pattern in debug mode so you can easily spot when accessing freed memory.

为什么这与您的问题相关?因为编译器通过 this 作为隐藏的隐式参数。

Why is this related to your question? Because the compilers passes this as a hidden, implicit parameter.

这篇关于在成员函数中使用“删除此”后,我可以访问其他成员函数。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆