Pointers/Memory Allocation   «Prev  Next»
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 new is used in the following forms:
  1. new type-name
  2. new type-name initializer
  3. new type-name[expression]
In each case there are at least two effects:
  1. An appropriate amount of store is allocated from free store to contain the named type.
  2. 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 new failed.

Examples

The following example uses new:
int* p, *q;
p = new int(5);    //allocate and initialize
q = new int[10];   //q[0] to q[9] with q = &q[0]

In this code, the pointer to int variable 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.