Operator new
Encyclopedia
In the C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

, as well as in many C++-based languages, new is a language construct that dynamically allocates memory
Memory
In psychology, memory is an organism's ability to store, retain, and recall information and experiences. Traditional studies of memory began in the fields of philosophy, including techniques of artificially enhancing memory....

 on the heap and initialises the memory using the constructor. Except for a form called the "placement new", new attempts to allocate enough memory on the heap for the new data. If successful, it initialises the memory and returns the address to the newly allocated and initialised memory. However if new cannot allocate memory on the heap it will throw an exception
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

 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 the heap, must be made for every call to new to avoid a memory leak
Memory leak
A memory leak, in computer science , occurs when a computer program consumes memory but is unable to release it back to the operating system. In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code...

.

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
Default constructor
In computer programming languages the term “default constructor” refers to a constructor that is automatically generated in the absence of explicit constructors ; this automatically provided constructor is usually a nullary 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-1]

gives the value of the nth element (counting from 0)

Memory allocated with new must be deallocated with delete to avoid a memory leak
Memory leak
A memory leak, in computer science , occurs when a computer program consumes memory but is unable to release it back to the operating system. In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code...

. 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)


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.

Implementation

In compilers conforming to the ISO C++ standard, if there is not enough memory for the allocation, the code throws an exception
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

 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
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...

 to define specific behaviors.

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;
delete p_var;
p_var = 0;

int *p_array = new int[50];
delete[] p_array;
p_array = 0;


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[]

In contrast to C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

'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
C++ standard library
In C++, the C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself...

 provides a dynamic array
Dynamic array
In computer science, a dynamic array, growable array, resizable array, dynamic table, or array list is a random access, variable-size list data structure that allows elements to be added or removed...

 that can be extended or reduced in its std::vector template
Vector (STL)
Vector is a class template in the C++ Standard Template Library, which functions like a dynamic array. It is one of several data structures called containers, some of the others being sets, maps, and lists. It is implemented as a class template, and can thus be used as a generic framework that may...

.

void* operator new(size_t size)

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 to define a class specific memory allocator.

See also

  • Allocators
  • Delete (C++)
  • Exception handling
    Exception handling
    Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

  • malloc
    Malloc
    C dynamic memory allocation refers to performing dynamic memory allocation in the C via a group of functions in the C standard library, namely malloc, realloc, calloc and free....

  • Memory pool
    Memory pool
    Memory pools, also called fixed-size-blocks allocation, allow dynamic memory allocation comparable to malloc or C++'s operator new. As those implementations suffer from fragmentation because of variable block sizes, it can be impossible to use them in a real time system due to performance...

  • Placement syntax
    Placement syntax
    In the C++ programming language, placement syntax allows programmers to explicitly specify the memory management of individual objects — i.e. their "placement" in memory. Normally, when an object is created dynamically, an allocation function is invoked in such a way that it will both allocate...

  • Pointers
  • Smart pointers
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK