Operator Delete
   HOME

TheInfoList



OR:

In the C++
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
, and are a pair of
language construct In computer programming, a language construct is "a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of the programming language", as defined by in the ISO/IEC 2382 stan ...
s that perform
dynamic memory allocation Memory management (also dynamic memory management, dynamic storage allocation, or dynamic memory allocation) is a form of resource management applied to computer memory. The essential requirement of memory management is to provide ways to dyna ...
, object construction and
object destruction Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ai ...
.


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 Default may refer to: Law * Default (law), the failure to do something required by law ** Default (finance) In finance, default is failure to meet the legal obligations (or conditions) of a loan, for example when a home buyer fails to make ...
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 a
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 objec ...
. 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 , 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, a program exhibits undefined behavior (UB) when it contains, or is executing code for which its programming language specification does not mandate any specific requirements. 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 a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior vers ...
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 In computing, a null pointer (sometimes shortened to nullptr or null) or null reference is a value saved for indicating that the Pointer (computer programming), pointer or reference (computer science), reference does not refer to a valid Object (c ...
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 object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. It is one of the well-known "Gang of Four" design patterns, which describe how to solve recur ...
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''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
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 standard library, sometimes referred to as libc, is the standard library for the C (programming language), C programming language, as specified in the ISO C standard.International Organization for Standardization, ISO/International Electrote ...
, 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 inclu ...
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" and sometimes abbreviated as CPP or CXX) is a high-level, general-purpose programming language created by Danish computer scientist Bjarne Stroustrup. First released in 1985 as an extension of the C programmi ...
") 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, sometimes referred to as 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 origina ...
instead provides a
dynamic array In computer science, a dynamic array, growable array, resizable array, dynamic table, mutable array, or array list is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard l ...
(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 and thus
deadlock Deadlock commonly refers to: * Deadlock (computer science), a situation where two processes are each waiting for the other to finish * Deadlock (locksmithing) or deadbolt, a physical door locking mechanism * Political deadlock or gridlock, a si ...
. Section 4.4, Common C++ Memory Management Errors.


See also

*
Allocator (C++) Allocation may refer to: Computing * Block allocation map * Allocator (C++), C++ allocators * Delayed allocation * File allocation table * IP address allocation * Memory allocation * Cache (computing), No-write allocation (cache) * Register all ...
*
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. Dynamic memory allocation can, and has been achieved through the use of techniques such as malloc and C ...
*
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 ''re ...
*
Resource Acquisition Is Initialization Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented, statically typed programming languages to describe a particular language behavior. In RAII, holding a resource is a class invariant, and is tie ...
(RAII) *
Smart pointers In computer science, a smart pointer is an abstract data type that simulates a Pointer (computer programming), pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce ...


References

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