Delete operation

Hi all

I came across a piece of code.

Myclass *x; //Creating an object of a class

while(condition)
{

x=getanother(); this function returns a pointer created using new.

if(condition)
{
delete x;

}


}


when i debugged the above code i came to see that the delete is called many times. but it is working perfectly.

What does delete actually do??


Please clarify my doubt.

regards
That code actually looks scary to me.

You should never try to delete something more than once. Some librarys can tolerate it, but it is not in the standard.

Quux* q = new Quux;
Allocates memory on the heap that is at least big enough to hold an object of class 'Quux'. Once there is memory for it, Quux's constructor is called (in this case, the default constructor). Then the address of the object is returned and stored in the pointer 'q'.

delete q; q = NULL;
This does the opposite. The destructor for the Quux object at the address in 'q' is called, then the memory used by the object is returned to the heap so that it can be used again.
Notice how I also immediately set 'q' to NULL. It is not strictly necessary to do that, but it is a good idea. That way if something else tries to use *q again it will definitely cause an error, so you know to fix it.

The code would be better as:
1
2
3
4
5
6
7
8
while (condition)
  {
  Myclass* x = getanother();

  x->dosomething();

  delete x;
  }

That is, always delete what you new. Failure to do that is a memory leak.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.