20.2 delete Operator

I l @ ve RuBoard

The operator new gets memory from the heap. To return the memory to the heap you use the operator delete . The general form of the delete operator is:

 delete   pointer   ;       // Where   pointer   is a pointer to a simple object   pointer   =     NULL; 

where pointer is a pointer previously allocated by new . If the new operator allocated an array, you must use the form:

 delete[]   pointer   ;       // Where   pointer   is a pointer to an array   pointer   =     NULL; 

There are two forms of the delete operator because there is no way for C++ to tell the difference between a pointer to an object and a pointer to an array of objects. The delete operator relies on the programmer using " [] " to tell the two apart.

If you accidentally omit the " [] " when deleting an array, C++ will think you are giving delete a pointer to a single object and will delete only that object.

Strictly speaking, the line:

   pointer   =     NULL; 

is unnecessary. However, it is a good idea to "null out" pointers after they are deleted. That way, you don't try use a pointer to deleted memory, and you also help prevent any attempts to delete the same memory twice.

The following is an example using new to get storage and delete to dispose of it:

 const DATA_SIZE = (16 * 1024); void copy(  )  {      char *data_ptr;     // Pointer to large data buffer     data_ptr = new char[DATA_SIZE];       // Get the buffer     /*       * Use the data buffer to copy a file       */      delete[] data_ptr;      data_ptr = NULL; } 

But what happens if we forget to free the memory? The buffer becomes dead. That is, the memory management system thinks it's being used, but no one is using it. (The technical term for this is a "memory leak.") If the delete statement is removed from the function copy , each successive call eats up another 16K of memory.

The other problem that can occur is using memory that has been freed. When delete is used, the memory is returned to the memory pool and can be reused. Using a pointer after a delete call is similar to an array index out-of-bounds error. You are using memory that belongs to someone else. This can cause unexpected results or program crashes.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net