New (c++)

From Wikipedia, the free encyclopedia

The correct title of this article is new (c++). The initial letter is shown capitalized due to technical restrictions.

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. The syntax 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(initiator);

where initiator is the initial value assigned to the new variable, or if type is of class type, initiator is the arguments to a constructor.

new can also create an array:

p_var = new type [size];

In this case, size determines how large of a one-dimensional array to create. The address of the first element is returned and stored into p_var, so

p_var[n - 1]

gives the value of the nth element

Arrays created with new cannot be initialized.

Memory allocated with new must be deallocated with delete to avoid a memory leak.

Contents

[edit] Implementation

If there is not enough memory for the allocation the code throws an exception, meaning that all subsequent code is aborted until either the program aborts abnormally or the error is handled in a try-catch block. There is no need for the programmer to write code that checks the value of the pointer. In most C++ implementations the new operator can be overloaded in order to define specific behaviors.

[edit] Releasing Dynamically Allocated Memory

Any memory dynamically allocated with new must be released with the delete command:

delete p_var;

Or, in the case of an array:

delete [] p_var;

[edit] See also

[edit] Reference