New (C )
   HOME

TheInfoList



OR:

In the
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
, and are a pair of language constructs that perform
dynamic memory allocation Memory management is a form of resource management applied to computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when ...
, object construction and
object destruction In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementa ...
.


Overview

Except for a form called the "placement new", the operator denotes a request for memory allocation on a process's heap. If sufficient memory is available, initialises the memory, calling object constructors if necessary, and returns the address to the newly allocated and initialised memory. A request, in its simplest form, looks as follows: p = new T; where is a previously declared pointer of type (or some other type to which a pointer can be assigned, such as a superclass of ). The
default constructor In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors (e.g. in Java), and is usually a nullary constructor. I ...
for , if any, is called to construct a instance in the allocated memory buffer. If not enough memory is available in the free store for an object of type , the request indicates failure by throwing an exception of type . This removes the need to explicitly check the result of an allocation. The deallocation counterpart of is , which first calls the destructor (if any) on its argument and then returns the memory allocated by back to the free store. Every call to must be matched by a call to ; failure to do so causes
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object ...
s. syntax has several variants that allow finer control over memory allocation and object construction. A function call-like syntax is used to call a different constructor than the default one and pass it arguments, e.g., p = new T(argument); calls a single-argument constructor instead of the default constructor when initializing the newly allocated buffer. A different variant allocates and initialises
arrays An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
of objects rather than single objects: p = new T This requests a memory buffer from the free store that is large enough to hold a contiguous array of objects of type , contiguously, and calls the default constructor on each element of the array. Memory allocated with the must be deallocated with the operator, rather than . Using the inappropriate form results in
undefined behavior In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavior ...
. C++ compilers are not required to generate a diagnostic message for using the wrong form. The
C++11 C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
standard specifies an additional syntax, p = new T ; that initializes each to .


Error handling

If cannot find sufficient memory to service an allocation request, it can report its error in three distinct ways. Firstly, the ISO C++ standard allows programs to register a custom function called a with the C++ runtime; if it does, then this function is called whenever encounters an error. The may attempt to make more memory available, or terminate the program if it can't. If no is installed, instead throws an exception of type . Thus, the program does not need to check the value of the returned pointer, as is the habit in C; if no exception was thrown, the allocation succeeded. The third method of error handling is provided by the variant form , which specifies that no exception should be thrown; instead, a null pointer is returned to signal an allocation error.


Overloading

The operator can be overloaded so that specific types (classes) use custom memory allocation algorithms for their instances. For example, the following is a variant of the
singleton pattern In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. One of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems ...
where the first call allocates an instance and all subsequent calls return this same instance: #include #include class Singleton ; This feature was available from early on in C++'s history, although the specific overloading mechanism changed. It was added to the language because
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
C++ programs tended to allocate many small objects with , which internally used the C allocator (see ); that, however, was optimized for the fewer and larger allocations performed by typical C programs. Stroustrup reported that in early applications, the C function was "the most common performance bottleneck in real systems", with programs spending up to 50% of their time in this function. .


Relation to malloc and free

Since standard C++ subsumes the C standard library, the
C dynamic memory allocation C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely , , , and . The C++ programming language includes t ...
routines , , and are also available to C++ programmers. The use of these routines is discouraged for most uses, since they do not perform object initialization and destruction. and were, in fact, introduced in the first version of C++ (then called "
C with Classes C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
") to avoid the necessity of manual object initialization. In contrast to the C routines, which allow growing or shrinking an allocated array with , it is not possible to change the size of a memory buffer allocated by . The
C++ standard library The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. ISO/IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it was ...
instead provides a dynamic array (collection) that can be extended or reduced in its template class. The C++ standard does not specify any relation between / and the C memory allocation routines, but and are typically implemented as wrappers around and . Mixing the two families of operations, e.g., 'ing 'ly allocated memory or 'ing 'd memory, causes undefined behavior and in practice can lead to various catastrophic results such as failure to release
locks Lock(s) may refer to: Common meanings *Lock and key, a mechanical device used to secure items of importance *Lock (water navigation), a device for boats to transit between different levels of water, as in a canal Arts and entertainment * ''Lock ...
and thus
deadlock In concurrent computing, deadlock is any situation in which no member of some group of entities can proceed because each waits for another member, including itself, to take action, such as sending a message or, more commonly, releasing a loc ...
. Section 4.4, Common C++ Memory Management Errors.


See also

*
Allocator (C++) In C++ computer programming, allocators are a component of the C++ Standard Library. The standard library provides several data structures, such as list and set, commonly referred to as containers. A common trait among these containers is their ...
*
Exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
*
Memory pool Memory pools, also called fixed-size blocks allocation, is the use of pools for memory management that allows dynamic memory allocation comparable to malloc or C++'s operator new. As those implementations suffer from fragmentation because ...
*
Pointer (computer programming) In computer science, a pointer is an object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped computer hardware. A pointer ''ref ...
* Resource Acquisition Is Initialization (RAII) * Smart pointers


References

{{Programming languages C++ Articles with example C++ code