Page 251 - DCAP404 _Object Oriented Programming
P. 251
Object-oriented Programming
Notes In this case, if the allocation of this block of memory failed, the failure could be detected by
checking if bobby took a null pointer value:
int * bobby;
bobby = new (nothrow) int [5];
if (bobby == 0) {
// error assigning memory. Take measures.
};
!
Caution This nothrow method requires more work than the exception method, since the
value returned has to be checked after each and every memory allocation.
Anyway this method can become tedious for larger projects, where the exception method is
generally preferred.
Operators delete and delete[]
Since the necessity of dynamic memory is usually limited to specific moments within a program,
once it is no longer needed it should be freed so that the memory becomes available again for
other requests of dynamic memory. This is the purpose of the operator delete, whose format is:
delete pointer;
delete [] pointer;
The first expression should be used to delete memory allocated for a single element, and the
second one for memory allocated for arrays of elements.
The value passed as argument to delete must be either a pointer to a memory block previously
allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << “How many numbers would you like to type? “;
cin >> i;
p= new (nothrow) int[i];
if (p == 0)
cout << “Error: memory could not be allocated”;
else
{
244 LOVELY PROFESSIONAL UNIVERSITY