new (C++)

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In the C++ programming language, as well as in many C++-based languages, new is a language construct that dynamically allocates memory from free store and initialises the memory using the constructor.[1] Except for a form called the "placement new", new attempts to allocate enough memory in free store for the new data. If successful, it initialises the memory and returns the address to the newly allocated and initialised memory.[2][3] However if new cannot allocate memory in free store it will throw an exception of type std::bad_alloc. This removes the need to explicitly check the result of an allocation. A call to delete, which calls the destructor and returns the memory allocated by new back to free store, must be made for every call to new to avoid a memory leak.[1]

Syntax[edit]

The syntax for new is:

p_var = new type_name;

where p_var is a previously declared pointer of type type_name. type_name can be any basic data type or user-defined object (enum, class, and struct included). If type_name 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 argument(s) 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 nth element (counting from 0).

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); //allocates an integer, set to 5. (same syntax as constructors)
int *p_array = new int[5];  //allocates an array of 5 adjacent integers. (undefined values)
int *cpp11_array = new int[5] {1, 2, 3, 4, 5};  //allocates an array of 5 adjacent integers initialized to {1, 2, 3, 4, 5}. (C++11 only)

In C++98 initializers cannot be specified for arrays created with new. When no initializer list is provided 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.

Implementation[edit]

In compilers conforming to the ISO C++ standard, if there is not enough memory for the allocation, a new_handler function will be called (if registered) until requested memory can be provided. If the new_handler fails to allocate enough memory or no new_handler is set, 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.[1]

Releasing dynamically allocated memory[edit]

Any memory dynamically allocated with new must be released with delete. The delete operator can be used in two ways: one for de-allocating memory allocated to arrays with new and the other for deleting single objects.

int *p_var = new int;
delete p_var;
p_var = nullptr;
 
int *p_array = new int[50];
delete[] p_array; 
p_array = nullptr;

Note that the compiler is not required to generate a diagnostic message for using the wrong delete. Furthermore, using the inappropriate deallocator will result in undefined behavior.

Reallocating memory allocated by new[][edit]

In contrast to C's realloc, it is not possible to directly reallocate memory allocated with new[]. 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. The C++ standard library provides a dynamic array that can be extended or reduced in its std::vector template.

void* operator new(size_t size)[edit]

The C++ language construct that only allocates memory is called void* operator new(size_t size). It is used by new in the allocation phase. It can be overridden per class or globally to define a specific memory allocator.

See also[edit]

References[edit]

  1. ^ a b c Savitch, Walter (2013). Absolute C++. Pearson. pp. 420–445. ISBN 0132846810. 
  2. ^ "IBM Documentation describing C++'s operator new". Retrieved 2013-11-06. 
  3. ^ "Microsoft Visual Studio operator new documentation". Retrieved 2013-11-06.