new and delete (C++)

In the C++ programming language, new and delete are a pair of language constructs that perform dynamic memory allocation, object construction and object destruction.[1]

Overview

Except for a form called the "placement new", the new operator denotes a request for memory allocation on a process's heap. If sufficient memory is available, new initialises the memory, calling object constructors if necessary, and returns the address to the newly allocated and initialised memory.[2][3] A new request, in its simplest form, looks as follows:

p = new T;

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

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

The deallocation counterpart of new is delete, which first calls the destructor (if any) on its argument and then returns the memory allocated by new back to the free store. Every call to new must be matched by a call to delete; failure to do so causes memory leaks.[1]

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

p = new T(argument);

calls a single-argument 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:

p = new T [N];

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

Memory allocated with the new[] must be deallocated with the delete[] operator, rather than 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,

p = new T[N] {initializer1, ..., initializerN};

that initializes each p[i] to initializeri+1.

Error handling

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

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

Overloading

The 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 new Singleton call allocates an instance and all subsequent calls return this same instance:[4]

 1 #include <cstddef>
 2 
 3 class Singleton;
 4 
 5 namespace {
 6 
 7 Singleton* g_instance = nullptr;
 8 std::size_t g_refcount = 0;
 9 
10 }  // namespace
11 
12 class Singleton {
13  public:
14   static void* operator new(std::size_t nbytes) {
15     if (g_instance == nullptr) {
16       g_instance = ::new Singleton;  // Use the default allocator.
17     }
18     g_refcount++;
19     return g_instance;
20   }
21 
22   static void operator delete(void* p) {
23     if (--g_refcount == 0) {
24       ::delete g_instance;
25       g_instance = nullptr;
26     }
27   }
28 };

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 new, which internally used the C allocator (see § 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 malloc was "the most common performance bottleneck in real systems", with programs spending up to 50% of their time in this function.[5]

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

Relation to malloc and free

Since standard C++ subsumes the C standard library, the C dynamic memory allocation routines malloc, calloc, realloc and 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.[6] new and delete were, in fact, introduced in the first version of C++ (then called "C with Classes") to avoid the necessity of manual object initialization.[5]

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

The C++ standard does not specify any relation between new/delete and the C memory allocation routines, but new and delete are typically implemented as wrappers around malloc and free.[7] Mixing the two families of operations, e.g., free'ing new'ly allocated memory or delete'ing malloc'd memory, causes undefined behavior and in practice can lead to various catastrophic results such as failure to release locks and thus deadlock.[8]

gollark: Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the transgression of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg​ex parsers for HTML will ins​tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil​l devour your HT​ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi​ght he com̡e̶s, ̕h̵i​s un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo​͟ur eye͢s̸ ̛l̕ik͏e liq​uid pain, the song of re̸gular exp​ression parsing will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖î̩́t́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*͑̾̾​̅ͫ͏g͛͆̾l̍ͫͥe̠̅s ͎a̧͈͖r̽̾̈́e n​ot rè̑ͧaͨl̃ͤ͂ ZA̡͊͠LGΌ ISͮ̂҉̯͈͕ TO͇̹ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ Hͨ͊̽E̾͛ͪ ͧ̾ͬCͭ̏ͥOͮ͏̮M͊̒̚Ȇͩ͌Sͯ̿̔
gollark: ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
gollark: ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆYOU HAVE INVOKED THE DARK ONE
gollark: ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
gollark: ++exec```javascriptconsole.log(!!"gollark")```

See also

References

  1. Savitch, Walter (2013). Absolute C++. Pearson. pp. 420–445. ISBN 0132846810.
  2. "IBM Documentation describing C++'s operator new". Archived from the original on 2013-01-03. Retrieved 2013-11-06.
  3. "Microsoft Visual Studio operator new documentation". Retrieved 2013-11-06.
  4. Lischner, Ray (2003). C++ In a Nutshell: A Desktop Quick Reference. O'Reilly. pp. 128–129.
  5. Stroustrup, Bjarne (1993). A History of C++: 1979–1991 (PDF). Proc. ACM History of Programming Languages Conf.
  6. Meyers, Scott (1998). Effective C++. Addison-Wesley. p. 21.
  7. Alexandrescu, Andrei (2001). Modern C++ Design: Generic Programming and Design Patterns Applied. Addison-Wesley. p. 68.
  8. Seacord, Robert C. (2013). Secure Coding in C and C++. Addison-Wesley. Section 4.4, Common C++ Memory Management Errors.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.