In C, variables are placed in the free store by using the sizeof() macro to determine the needed allocation size and then calling malloc() with that size. Variables are removed from the free store by calling free(). With classes, using malloc() and free() becomes tedious. C++ provides the operators new and delete, which can allocate not only built-in types but also user-defined types. This provides a uniform mechanism for allocating and deallocating memory from the free store.
For example, to allocate an integer:
int *pi;
pi = new int;
*pi = 1;
and to allocate an array of 10 ints:
int *array = new int [10];
for (int i=0;i < 10; i++)
array[i] = i;
Just as with malloc() the memory returned by new is not initialized; only static memory has a default initial value of zero.
Suppose we have defined a type for complex numbers, called complex. We can dynamically allocate a complex number as follows:
complex* pc = new complex (1, 2);
In this case, the complex pointer pc will point to the complex number 1 + 2i.
All memory allocated using new should be deallocated using delete. However, delete takes on different forms depending on whether the variable being deleted is an array or a simple variable. For the complex number above, we simply call delete:
delete pc;
Delete calls the destructor for the object to be deleted. However, to delete each element of an array, you must explicitly inform delete that an array is to be deleted:
delete [] array;
The C++ compiler maintains information about the size and number of objects in an array and retrieves this information when deleting an array. The empty bracket pair informs the compiler to call the class destructor for each element in the array.
Be careful, attempting to delete a pointer that has not been initialized by new results in undefined program behavior. However, it is safe to apply the delete operator to a null pointer.
New and delete are global C++ operators and can be redefined (e.g., if it is desirable to trap every memory allocation). This is useful in debugging, but is not recommended for general programming. More often, the operators new and delete are overridden by providing new and delete operators for a specific class.
When C++ allocates memory for a user-defined class, the new operator for that class is used if it exists, otherwise the global new is used. Most often, programmers define new for certain classes to achieve improved memory management (i.e., reference counting for a class).
No comments:
Post a Comment