previous | start | next

20. The delete Operator

If a function uses new to allocate memory, this memory is not released when the function returns!

It is the C++ programmer's responsibility to explicitly release memory when it is no longer used.

The delete operator is a unary operator that returns no value. Its operand must evaluate to the address of a memory location that was returned previously by the new operator!

Example 1: Create an integer with new,use it then release it.

 int *p = new int;
 cin >> *p;
 ... 
 delete p; 

Note: delete p doesn't delete p! It releases the memory whose address is stored in p.

Example 2: Create an array of doubles, do something with them (not shown), the relase the dynamic array.

double *q = new double[1000];

for(int i = 0; i < 1000; i++) {
   q[i] = sqrt(i);
}
...
delete [] q;

It is annoying to have to include the [] when releasing the memory for a dynamic array, but the close connection between pointers and arrays creates a subtle difference between including the square brackets, [], and not. So we are stuck with including the square brackets for 99.9999% of the the cases we want to delete a dynamic array.



previous | start | next