The new operator attempts to dynamically allocate (at run time) one or more objects of type-name. The new operator cannot be used to allocate a function; however, it can be used to allocate a pointer to a function.
Syntax
allocation-expression :
::opt new placementopt new-type-name new-initializeropt
::opt new placementopt ( type-name ) new-initializeropt
placement :
( expression-list )
new-type-name :
type-specifier-list new-declaratoropt
The new operator is used to allocate objects and arrays of objects. The new operator allocates from a program memory area called the “free store.” In C, the free store is often referred to as the “heap.”
When new is used to allocate a single object, it yields a pointer to that object; the resultant type is new-type-name * or type-name *. When new is used to allocate a singly dimensioned array of objects, it yields a pointer to the first element of the array, and the resultant type is new-type-name * or type-name *. When new is used to allocate a multidimensional array of objects, it yields a pointer to the first element of the array, and the resultant type preserves the size of all but the leftmost array dimension. For example:
new float[10][25][10]
yields type float (*)[25][10]
. Therefore, the following code will not work because it attempts to assign a pointer to an array of float
with the dimensions [25][10]
to a pointer to type float
:
float *fp;
fp = new float[10][25][10];
The correct expression is:
float (*cp)[25][10];
cp = new float[10][25][10];
The definition of cp
allocates a pointer to an array of type float
with dimensions [25][10]
— it does not allocate an array of pointers.
All but the leftmost array dimensions must be constant expressions that evaluate to positive values; the leftmost array dimension can be any expression that evaluates to a positive value. When allocating an array using the new operator, the first dimension can be zero — the new operator returns a unique pointer.
The type-specifier-list cannot contain const, volatile, class declarations, or enumeration declarations. Therefore, the following expression is illegal:
volatile char *vch = new volatile char[20];
The new operator does not allocate reference types because they are not objects.
If there is insufficient memory for the allocation request, by default operator new returns NULL. You can change this default behavior by writing a custom exception-handling routine and calling the _set_new_handler run-time library function with your function name as its argument. For more details on this recovery scheme, see The operator new Function.