Compartilhar via


new Operator

C++ Specific —>

[::] new [placement] type-name [initializer]

[::] new [placement] (type-name) [initializer]

The new keyword allocates memory for an object of type-name from the free store and returns a suitably typed, nonzero pointer to an object. If unsuccessful, by default new returns zero. You can change this default behavior by writing a custom exception-handling routine and calling the _set_new_handler run-time library function with your function name as its argument.

Use the delete operator to deallocate the memory allocated with the new operator.

The following list describes the elements of new:

placement

Provides a way of passing additional arguments if you overload new.

type-name

Specifies type to be allocated. If the type specification is complicated, it can be surrounded by parentheses to force the order of binding.

initializer

Provides a value for the initialized object. Initializers cannot be specified for arrays. The new operator will create arrays of objects only if the class has a default constructor.

END C++ Specific

Examples

The following statement allocates an integer.

int *pi = new int;

The following statement allocates a character and initializes it.

char *pc = new char( 'a' );

The following statement allocates an instance of Date using the class's three-argument constructor, and returns a pointer to it.

Date *pmc = new Date( 3, 12, 1985 );

The following statement allocates an array of characters.

char *pstr = new char[sizeof( str )];

The following statement allocates a two-dimensional array of characters of size dim * 10. When allocating a multidimensional array, all dimensions except the first must be constant expressions.

char (*pchar)[10] = new char[dim][10];

The following statement allocates an array of seven pointers to functions that return integers.

int (**p) () = new (int (*[7]) ());

If you use the operator new without any extra arguments, and compile with the /GX, /EHs, or /EHa option, the compiler will generate code to call operator delete if the constructor throws an exception.

If you use the placement new form of the new operator, the form with arguments in addition to the size of the allocation, the compiler does not support a placement form of the delete operator if the constructor throws an exception.

Example

class A {
public:
    A(int) { throw "Fail!"; }
};
void foo(void)
{
    try {
        // heap memory pointed to by pa1 will be deallocated
        // by calling ::operator delete(void*).
        A* pa1 = new A(10);
    } catch (...) {
    }
    try {
        // This will call ::operator new(size_t, char*, int).
        // When A::A(int) does a throw, we should call
        // ::operator delete(void*, char*, int) to deallocate
        // the memory pointed to by pa2, but that's something
        // we don't support yet, so we'll leak memory.
        A* pa2 = new(__FILE__, __LINE__) A(20);
    } catch (...) {
    }
}