What will happen if I say delete this

Questions by suji   answers by suji

Showing Answers 1 - 23 of 23 Answers

we should not delete this pointer. This pointer always contains the address of the object in the scope. Deleting this pointer is like cutting a tree branch by standing on the same.

This pointer is not used to access static functions, since static function is for a class not for an object.

madhav

  • Nov 8th, 2005
 

if you say "delete this", you are effectively calling the destructor twice, which could well be a disaster if your class uses heap. The destructor will be called when you say " delete this " and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice. Please refrain from forcibaly calling a destructor or using clause like this. For more information, visit the following link: http://www.parashift.com/c++-faq-lite/dtors.html question 11.5

rkoshy

  • Sep 11th, 2008
 

Actually, I have rather good code that calls "delete this" -- and works very well, and without issues.  Under controlled situations, it is actually possible, and desirable to do this (for many reasons).

The issue here is that:
a) It should NEVER be used from classes that can be instantiated on the stack, i.e. a scoped variable that may go out of scope and destruct itself.
b) It can be used safely from a dynamically allocated class that is never 'deleted' by code that uses it.

Both of these can be prevented by using private/protected constructor & destructor.
   -

mucdull

  • Nov 17th, 2008
 

If this is done for an object allocated on the stack, the destructor will be called followed by a corruption of the heap. Your program will most likely give a seg fault.

If this is done for an object allocated on the heap, the destructor will be called and your object will be destructed and deallocated. Any further use of the object gives undefined behavior, most likely resulting in a seg fault as well.

AlTel

  • Apr 20th, 2009
 

Check this:
class X
{
public:
    X() {}
    void destroy() const { delete this; }
protected:
    ~X() {}
};

int main()
{
X *xx = new X();
xx->destroy();
}

This is correct and legal, it is global var and destructor will never called automatically. Why somebody need this ? For example
1)you want to implement your garbage collector
2)make sure that no one destroy your object ever (then you dont need destroy())
3)just want to prevent local instantiation (only via new()).
Regards
Aleksey

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions