After using 'delete this' in a member function I am able to access other member functions. Why?

徘徊边缘 提交于 2019-11-28 14:19:58
Werner Henze

Let's compare that to a similar szenario:

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

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.

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

dasblinkenlight
  1. What you see is undefined behavior: it might work, or it may crash.
  2. The pointer is pointing to a deleted instance - it is a dangling pointer.
  3. This is an undefined behavior as well: you may see a zero or a garbage value.

Eric Lippert provided a very nice "book in a table drawer of a hotel room" analogy in his answer to a question about pointers to local variables after the function has returned, it is equally applicable here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!