The new operator allocates dynamic memory and returns a pointer of the appropriate type to it. Its general form is shown here:

p_var = new type;

Here, p_var is a pointer variable that will receive the address of the allocated memory, and type is the type of data that the memory will hold. The new operator automatically allocates sufficient memory to hold one item of data of the specified type. For example, this code fragment allocates sufficient memory to hold a double:

double *p; p = new double;

If the allocation request fails, a bad_alloc exception is thrown.

NOTE: Older compilers may exhibit a different behavior on allocation failure than just described. For example, it is possible that no exception will be thrown and that a null pointer will be returned. Check your compiler’s documentation for information that applies to your current working environment.

You can initialize the allocated memory by specifying an initializer, using this general form:

p_var = new type (initializer);

Here, initializer is the value that will be assigned to the allocated memory.

To allocate a single-dimension array, use the following general form:

p_var = new type[size];

Here, size specifies the length of the array. new will automatically allocate sufficient room to hold an array of the specified type and of the specified size. When allocating arrays, no initializations may be given.

If your C++ compiler fully complies with the ANSI/ISO standard, then it supports a “no-throw” form of new, which has this general form:

p_var = new(nothrow) type;

The nothrow form of new returns a null if an allocation failure occurs, rather than throwing an exception. To use this form, your program must include the header <new>.

There is also a placement form of new, which lets you pass one or more arguments to an overloaded version of new. It has this general form.

p_var = new (arg-list) type;

Here, the values in arg-list are passed to the overloaded new operator function.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net