new (C++)

new (C++)

In the C++ programming language, as well as in many C++-based languages, new is a language construct that dynamically allocates memory on the heap and initialises the memory using the constructor. Except for a form called the "placement new", new attempts to allocate enough memory on the heap for the new data. If successful, it initialises the memory and returns the address to the newly allocated and initialised memory. However if new cannot allocate memory on the heap it will throw an exception of type std::bad_alloc. This removes the need to explicitly check the result of an allocation. A call to delete, which calls the destructor and returns the memory allocated by new back to the heap, must be made for every call to new to avoid a memory leak.

Contents

Syntax

The syntax for new is:

p_var = new typename;

where p_var is a previously declared pointer of type typename. typename can be any basic data type or user-defined object (enum, class, and struct included). If typename is of class type, the default constructor is called to construct the object.

To initialize a new variable created via new, use the following syntax:

p_var = new type(initializer);

where initializer is the initial value assigned to the new variable, or if type is of class type, initializer is the argument(s) to a constructor.

new can also create an array:

p_var = new type [size];

In this case, size specifies the length of one-dimensional array to create. The address of the first element is returned and stored into p_var, so

p_var[n-1]

gives the value of the nth element (counting from 0)

Memory allocated with new must be deallocated with delete to avoid a memory leak. Arrays allocated with new[] must be deallocated with delete[].

int *p_scalar = new int(5); //allocates an integer, set to 5. (same syntax as constructors)
int *p_array = new int[5];  //allocates an array of 5 adjacent integers. (undefined values)

Initializers cannot be specified for arrays created with new. All elements of an array are initialized with the default constructor of the type. If the type does not have a default constructor, this is a compile-time error.

Implementation

In compilers conforming to the ISO C++ standard, if there is not enough memory for the allocation, the code throws an exception of type std::bad_alloc. All subsequent code is aborted until the error is handled in a try-catch block or the program exits abnormally. The program does not need to check the value of the pointer; if no exception was thrown, the allocation succeeded. The implemented operations are defined in the header <new>. In most C++ implementations the new operator can also be overloaded to define specific behaviors.

Releasing dynamically allocated memory

Any memory dynamically allocated with new must be released with a delete command. There are two variants: one for arrays and one for single objects.

int *p_var = new int;
delete p_var;
p_var = 0;
 
int *p_array = new int[50];
delete[] p_array; 
p_array = 0;

Note that the compiler is not required to generate a diagnostic message for using the wrong delete. Furthermore, using the inappropriate deallocator will result in undefined behavior.

Reallocating memory allocated by new[]

In contrast to C's realloc, it is not possible to directly reallocate memory allocated with new[]. To extend or reduce the size of a block, one must allocate a new block of adequate size, copy over the old memory, and delete the old block. The C++ standard library provides a dynamic array that can be extended or reduced in its std::vector template.

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

See also

References


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать курсовую

Look at other dictionaries:

  • New — (n[=u]), a. [Compar. {Newer} (n[=u] [ e]r); superl. {Newest}.] [OE. OE. newe, AS. niwe, neowe; akin to D. nieuw, OS. niwi, OHG. niuwi, G. neu, Icel. n[=y]r, Dan. & Sw. ny, Goth. niujis, Lith. naujas, Russ. novuii, Ir. nua, nuadh, Gael. nuadh, W.… …   The Collaborative International Dictionary of English

  • New I/O — New I/O, usually called NIO, is a collection of Java programming language APIs that offer features for intensive I/O operations. It was introduced with the J2SE 1.4 release of Java by Sun Microsystems to complement an existing standard I/O. NIO… …   Wikipedia

  • New — (n[=u]), adv. Newly; recently. Chaucer. [1913 Webster] Note: New is much used in composition, adverbially, in the sense of newly, recently, to qualify other words, as in new born, new formed, new found, new mown. [1913 Webster] {Of new}, anew.… …   The Collaborative International Dictionary of English

  • New FM — City of license Newcastle Slogan Hottest Songs from the 80 s, 90 s and Today Frequency 105.3 MHz First air date 6 May 1989 ( …   Wikipedia

  • NEW — ist: das IATA Kürzel für den New Orleans Lakefront Airport das Kfz Kennzeichen des Landkreises Neustadt an der Waldnaab new ist: das Kürzel für die Sprache Newari nach ISO 639 2 New ist ein englischer Familienname. Harry S. New (1858–1937), US… …   Deutsch Wikipedia

  • New — Cette page d’homonymie répertorie les différents sujets et articles partageant un même nom. NEW, sigle composé des trois lettres N, E et W, peut faire référence à : Lakefront Airport, un aéroport régional de la Nouvelle Orléans en Louisiane …   Wikipédia en Français

  • New — New, v. t. & i. To make new; to renew. [Obs.] [1913 Webster] …   The Collaborative International Dictionary of English

  • New TV — est une chaîne de télévision fondée par Tahsin Khayat. Elle se situe à Beyrouth, spécifiquement à la Mazraa . Son service politique est dirigé par la journaliste Maria Maalouf …   Wikipédia en Français

  • New (C++) — In the C++ programming language, new is an operator that allows dynamic memory allocation on the heap. new attempts to allocate enough memory on the heap for the new data and, if successful, returns the address to the newly allocated… …   Wikipedia

  • new — I. adjective Etymology: Middle English, from Old English nīwe; akin to Old High German niuwi new, Latin novus, Greek neos Date: before 12th century 1. having recently come into existence ; recent, modern 2. a. (1) having been seen, used, or known …   New Collegiate Dictionary

  • New — To start a new article in Wikipedia, see Help:Starting a new article. New is an adjective referring to something recently made, discovered, or created. New or NEW may refer to: Contents 1 Film and music 2 …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”