| Lesson 9 || Free store operators |
| Objective || The operator new |
C++ new operator
Examine use of the operator new to allocate free store memory.
In C++, the operator
is used in the following forms:
new type-name initializer
In each case there are at least two effects:
- An appropriate amount of store is allocated from free store to contain the named type.
- The base address of the variable is returned as the value of the
new expression. The operator
new returns the value 0 when memory is unavailable. This value should be tested to see if
new failed. C++ systems can also throw an allocation exception indicating
The following example uses
int* p, *q;
p = new int(5); //allocate and initialize
q = new int; //q to q with q = &q
In this code, the pointer to
p is assigned the address of the store obtained in allocating an object of type
int. The location pointed at by
p is initialized to the value 5.
This use is not usual for a simple type such as
int, in that it is far more convenient and natural to automatically allocate an integer variable on the stack or globally. More usual is the allocation to the pointer
q of an array of elements.