Wednesday, September 1, 2010

What will happen if when say delete this ?

There are two scenarios:

1. Using "delete this;" in destructor

Here the call will be a recursive call to the destructor
infinitely. So the program hangs here.

2. Using "delete this;" in other members of a class
including constructor.

In this case, the call is a sucide call since the object
tries to delete itself which is nothing but sitting in a
space and destroy that space itself. That is definitely a
memory crash.



Using delete this in destructor will lead to recursive loop
which will lead to Stack overflow...so avoid it over
here...however there are few times where your code with
delete this will just work fine..like in the usage of
garbage colletors in C++.Chk the below code...which works
with no issues:
class temp
{
public:
temp(){std::cout<<"Constructor"<destroy();
return 0;
}

No comments:

Post a Comment