{{short description|C++ programming keywords for dynamic memory allocation}} {{Lowercase title}} In the C++ programming language, {{mono|'''new'''}} and {{mono|'''delete'''}} are a pair of language constructs that perform dynamic memory allocation, object construction and object destruction.<ref name="Savitch">{{cite book |title=Absolute C++ |year=2013 |publisher=Pearson |last=Savitch |first=Walter |isbn=978-0132846813 |pages=420–445}}</ref>

==Overview== Except for a form called the "placement new", the {{code|new}} operator denotes a request for memory allocation on a process's heap. If sufficient memory is available, {{code|new}} initialises the memory, calling object constructors if necessary, and returns the address to the newly allocated and initialised memory.<ref name="IBM">{{cite web |url=http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc05cplr199.htm |archive-url=https://archive.today/20130103101712/http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc05cplr199.htm |url-status=dead |archive-date=2013-01-03 |title=IBM Documentation describing C++'s operator new |access-date=2013-11-06 }}</ref><ref name="USBM">{{cite web |url=https://msdn2.microsoft.com/en-us/library/kewsb8ba(VS.71).aspx |title=Microsoft Visual Studio operator new documentation |access-date=2013-11-06}}</ref> A {{mono|new}} request, in its simplest form, looks as follows:

<syntaxhighlight lang="cpp"> T* p = new T; T* p = new T(); // zero-initialises primitives </syntaxhighlight>

where {{code|p}} is a pointer of type {{code|T}} (or some other type to which a {{code|T}} pointer can be assigned, such as a superclass of {{code|T}}). The default constructor for {{code|T}}, if any, is called to construct a {{code|T}} instance in the allocated memory buffer.

If not enough memory is available in the free store for an object of type {{code|T}}, the {{code|new}} request indicates failure by throwing an exception of type {{code|std::bad_alloc}}. This removes the need to explicitly check the result of an allocation.

The deallocation counterpart of {{code|new}} is {{code|delete}}, which first calls the destructor (if any) on its argument and then returns the memory allocated by {{code|new}} back to the free store. Every call to {{code|new}} must be matched by a call to {{code|delete}}; failure to do so causes a memory leak.<ref name="Savitch" />

{{mono|new}} 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.,

<syntaxhighlight lang="cpp"> T* p = new T(argument); </syntaxhighlight>

calls a single-argument {{code|T}} constructor instead of the default constructor when initializing the newly allocated buffer.

A different variant allocates and initialises arrays of objects rather than single objects: <syntaxhighlight lang="cpp"> T* p = new T[N]; </syntaxhighlight>

This requests a memory buffer from the free store that is large enough to hold a contiguous array of {{code|N}} objects of type {{code|T}}, and calls the default constructor on each element of the array.

Memory allocated with the {{code|new[]}} must be deallocated with the {{code|delete[]}} operator, rather than {{code|delete}}. Using the inappropriate form results in undefined behavior. C++ compilers are not required to generate a diagnostic message for using the wrong form.

The C++11 standard specifies an additional syntax,

<syntaxhighlight lang="cpp"> constexpr size_t N = /* some length */;

T* p = new T[N] {initializer1, ..., initializerN}; </syntaxhighlight>

that initializes each {{mono|p[''i'']}} to {{mono|initializer<sub>''i''+1</sub>}}.

Java and C# have the <code>new</code> operator (which calls the class constructor), but not the <code>delete</code> operator. Java does not have destructors. C# has destructors, but they are seldomly used and cannot be called through the <code>delete</code> operator.

<syntaxhighlight lang="java"> public class Person { private String name; private int age;

public Person(String name, int age) { this.name = name; this.age = age; } }

Person p = new Person("Alice", 30); </syntaxhighlight>

Although in Rust there are no object-oriented style constructors, the convention is to name a factory method for instantiating a struct <code>new</code> (usually returning <code>Self</code>), while manual deletion is done by implementing <code>std::ops::Drop</code>.<ref>{{Cite web | url=https://doc.rust-lang.org/stable/reference/destructors.html | title=Destructors - the Rust Reference }}</ref>

JavaScript and TypeScript have the operators <code>new</code> and <code>delete</code>. However, while <code>new</code> is used for calling the class constructor, <code>delete</code> does not call a destructor (as destructors do not exist in JavaScript or TypeScript). Instead, <code>delete</code> removes a property from an object.

<syntaxhighlight lang="typescript"> class User { name: string; age?: number; // marked optional to allow delete

constructor(name: string, age?: number) { this.name = name; this.age = age; } }

let user: User = new User("Alice", 30);

delete user.age; // No TypeScript error

// Output: { name: "Alice" } console.log(user); </syntaxhighlight>

In C++, <code>delete</code> is also used to disable compiler-generated methods, such as default constructors. In C++26, it is possible to provide a reason for its removal. <syntaxhighlight lang=cpp> class NonCopyable { public: NonCopyable() = default; NonCopyable(const NonCopyable&) = delete("No copy constructor"); NonCopyable& operator=(const NonCopyable&) = delete("No copy assignment"); }; </syntaxhighlight>

===Error handling=== If {{code|new}} 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 {{code|new_handler}} with the C++ runtime; if it does, then this function is called whenever {{code|new}} encounters an error. The {{code|new_handler}} may attempt to make more memory available, or terminate the program if it can't.

If no {{code|new_handler}} is installed, {{code|new}} instead throws an exception of type {{code|std::bad_alloc}}. 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 {{code|new(std::nothrow)}}, which specifies that no exception should be thrown; instead, a null pointer is returned to signal an allocation error.

===Overloading=== The {{code|new}} 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 where the first {{code|new Singleton()}} call allocates an instance and all subsequent calls return this same instance:

<syntaxhighlight lang="c++"> import std;

class Singleton { private: static void* instance = nullptr; static size_t refcount = 0; public: static void* operator new(size_t size) { if (!instance) { instance = std::malloc(size); } ++refcount; return instance; }

static void operator delete(maybe_unused void* p) noexcept { if (--refcount == 0) { std::free(instance); instance = nullptr; } } }; </syntaxhighlight>

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 C++ programs tended to allocate many small objects with {{code|new}}, which internally used the C allocator (see {{slink||Relation to malloc and free}}); that, however, was optimized for the fewer and larger allocations performed by typical C programs. Stroustrup reported that in early applications, the C function {{code|malloc()}} was "the most common performance bottleneck in real systems", with programs spending up to 50% of their time in this function.{{r|history}}

==Relation to malloc and free== Since standard C++ subsumes the C standard library, the C dynamic memory allocation routines {{code|malloc()}}, {{code|calloc()}}, {{code|realloc()}} and {{code|free()}} 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.<ref>{{Cite book |title=Effective C++ |url=https://archive.org/details/effectivecspecif00meye_047 |url-access=limited |first=Scott |last=Meyers |author-link=Scott Meyers |publisher=Addison-Wesley |year=1998 |page=[https://archive.org/details/effectivecspecif00meye_047/page/n37 21]|isbn=9780201924886 }}</ref> {{code|new}} and {{code|delete}} were, in fact, introduced in the first version of C++ (then called "C with Classes") to avoid the necessity of manual object initialization.<ref name="history">{{cite conference |first=Bjarne |last=Stroustrup |author-link=Bjarne Stroustrup |title=A History of C++: 1979–1991 |conference=Proc. ACM History of Programming Languages Conf. |year=1993 |url=https://www.stroustrup.com/hopl2.pdf}}</ref>

In contrast to the C routines, which allow growing or shrinking an allocated array with {{code|realloc()}}, it is not possible to change the size of a memory buffer allocated by {{code|new[]}}. The C++ standard library instead provides a dynamic array (collection) that can be extended or reduced in its {{mono|std::vector}} template class.

The C++ standard does not specify any relation between {{code|new}}/{{code|delete}} and the C memory allocation routines, but {{code|new}} and {{code|delete}} are typically implemented as wrappers around {{code|malloc()}} and {{code|free()}}.<ref>{{Cite book |title=Modern C++ Design: Generic Programming and Design Patterns Applied |url=https://archive.org/details/cmoderncdesignge00alex |url-access=limited |first=Andrei |last=Alexandrescu |publisher=Addison-Wesley |year=2001 |page=[https://archive.org/details/cmoderncdesignge00alex/page/n82 68]}}</ref> Mixing the two families of operations, e.g., {{code|free()}}-ing {{code|new}}-ly allocated memory or {{code|delete}}-ing {{code|malloc()}}-ed memory, causes undefined behavior and in practice can lead to various catastrophic results such as failure to release locks and thus deadlock.<ref name="secure">{{cite book |title=Secure Coding in C and C++ |first=Robert C. |last=Seacord |publisher=Addison-Wesley |year=2013}} Section 4.4, Common C++ Memory Management Errors.</ref>

==See also== * Allocator (C++) * Exception handling * Memory pool * Pointer (computer programming) * Resource Acquisition Is Initialization (RAII) * Smart pointers * Placement syntax

==References== {{reflist}}

{{C++ programming language}} {{Memory management navbox}} {{Programming languages}}

Category:C++ Category:Articles with example C++ code