Monday, 22 April 2013

new and delete Operators

new and delete are used for dynamic allocation of memory space. They have a major
advantage over malloc and free: constructors and destructors (see 2.2.4) for the objects
created or destroyed will be called.
There are two forms of new and delete, depending on whether a single object or an array
of objects is required:
pf = new float; for a single float
pf = new float [ num ]; for an array of floats
You should use the corresponding form of delete when destroying the objects created with
new, i.e.
delete pf; for a single object
delete [] pf; for an array of objects
This will ensure that the destructor is called for each object in the array.
new returns 0 (NULL) on failure.
The following example program illustrates the use of new and delete.
#include <stdio.h>
int main()
{
int num_chars;
char *name;
printf("how many characters in your string? ");
scanf("%d",&num_chars);
name = new char [num_chars + 1];
// allocate enough room for num_chars characters
// + 1 for the '\0'
if (name != NULL) {
// do something with name
delete [] name;
// remove name from the heap
}
return 0;
}
It is possible to set up a function to handle out of memory errors when using new; the
function set_new_handler (declared in new.h) is used to register the handler:
#include <iostream.h>
#include <new.h>
#include <stdlib.h>
#include <limits.h>
void newError()
{
fprintf(stderr,"new failed: out of memory\n");
exit(1);
}
int main()
{
char *ptr;
set_new_handler(newError);
ptr = new char [ULONG_MAX];
return 0;
}
This program sets up a handler that prints an error message and aborts the program if the
heap is full.

No comments:

Post a Comment