Run-time allocation and deallocation - new and delete
Declaring variables statically
This is fine, as long as we know everything beforehand.
What if we don't?
If we don't know how many variables we will need, we have to declare, for example, an array that is bigger than the maximum we might want.
Even this isn't always possible.
Example:
To use this, declare a pointer to the object type you want, then assign it the value of the new operation.
Example:
Note that we don't actually have a name for the integer itself, just a pointer.
An object created with new
If we change the value of the pointer, without saving it somewhere, we have lost the object.
Example
In this case, the first int still exists, but we can no longer access it.
Allocating arrays with new.
Arrays are just pointers to some memory.
For example, a sort program could take an unsorted list and return a pointer to a sorted list.
int *sort(int *unsorted, int size) { int *sorted = new[size]; // sort unsorted and put the result in sorted return(sorted); }To use this, a program might look like this
main() { int num_elements; int i; int *unsorted; int *sorted; cout << "Please enter the number of elements in the list" << endl; cin >> num_elements; unsorted = new int[num_elements]; for(i = 0; i < num_elements; i++) { cout << "Please enter element " << i << ": "; cin >> unsorted[i]; } sorted = sort(unsorted, num_elements); cout << "The sorted list:" << endl; for(i = 0; i < num_elements; i++) { cout << sorted[i] << endl; } return(); }
The delete operator
The new operator creates an object that lives for the duration of the program.
The object does not get destroyed as soon as you exit the function in which it was created.
delete destroys objects created dynamically
It takes a pointer to the object as input
Example:
The list class