Jump to content

new and delete (C++)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 107.77.218.55 (talk) at 02:46, 6 October 2016 (/* Overview "). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.


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]

Relation to malloc and free

Since standard C++ subsumes the C standard library, the C dynamic memory allocation routines malloc, 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.[2] 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.[3]

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.[4] 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.[5]

See also

References

  1. ^ Savitch, Walter (2013). Absolute C++. Pearson. pp. 420–445. ISBN 0132846810.
  2. ^ Meyers, Scott (1998). Effective C++. Addison-Wesley. p. 21.
  3. ^ Stroustrup, Bjarne (1993). A History of C++: 1979–1991 (PDF). Proc. ACM History of Programming Languages Conf.
  4. ^ Alexandrescu, Andrei (2001). Modern C++ Design: Generic Programming and Design Patterns Applied. Addison-Wesley. p. 78.
  5. ^ Seacord, Robert C. (2013). Secure Coding in C and C++. Addison-Wesley. Section 4.4, Common C++ Memory Management Errors.