new (C++)
From Wikipedia, the free encyclopedia
In the C++ programming language, new is an operator that allows dynamic memory allocation on the heap. new
attempts to allocate enough memory on the heap for the new data and, if successful, returns the address to the newly allocated memory.
Contents |
[edit] Syntax
The syntax for new
is:
-
p_var = new typename;
where p_var
is a previously declared pointer of type typename
. typename
can be any basic data type or user-defined object (enum
, class
, and struct
included). If typename
is of class type, the default constructor is called to construct the object.
To initialize a new variable created via new
, use the following syntax:
-
p_var = new type(initializer);
where initializer
is the initial value assigned to the new variable, or if type
is of class type, initializer
is the arguments to a constructor.
new
can also create an array:
-
p_var = new type [size];
In this case, size
specifies the length of one-dimensional array to create. The address of the first element is returned and stored into p_var
, so
-
p_var[n]
gives the value of the n
th element (counting from zero)
Memory allocated with new
must be deallocated with delete
to avoid a memory leak. Arrays allocated with new[]
must be deallocated with delete[]
.
int* p_scalar = new int(5); int* p_array = new int[5];
Initializers cannot be specified for arrays created with new
. All elements of an array are initialized with the default constructor of the type. If the type does not have a default constructor, this is a compile-time error.
[edit] Implementation
In compilers conforming to the ISO C++ standard, if there is not enough memory for the allocation, the code throws an exception of type std::bad_alloc
. All subsequent code is aborted until the error is handled in a try-catch block or the program exits abnormally. The program does not need to check the value of the pointer; if no exception was thrown, the allocation succeeded. The implemented operations are defined in the header <new>
. In most C++ implementations the new
operator can also be overloaded to define specific behaviors.
[edit] Releasing dynamically allocated memory
Any memory dynamically allocated with new
must be released with a delete
command. There are two variants: one for arrays and one for single objects.
int *p_var = new int; int *p_array = new int[50]; delete p_var; delete[] p_array;
Note that the compiler will generate neither a warning nor an error for using the wrong delete
; it cannot know in general whether a pointer is to a single element or an array of elements. Furthermore, using the inappropriate deallocator can result in undefined behavior.
[edit] Reallocating memory allocated by new[]
In contrast to C's realloc
, it is not directly possible to reallocate memory allocated by new[]
; in order to extend or reduce the size of a block, one must allocate a new block of adequate size, copy over the old memory, and delete the old block.