Export (0) Print
Expand All

new Operator

Grammar

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

The new keyword allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object. If unsuccessful, by new returns zero or throws an exception; see The new and delete Operators for more information. 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.

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.

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

The following list describes the grammar elements of new:

placement
Provides a way of passing additional arguments if you overload new.
type-name
Specifies type to be allocated; it can be either a built-in or user-defined type. 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.

Examples

The following code example allocates a character array and an object of class CName and then frees them.

// expre_new_Operator.cpp
// compile with: /EHsc
#include <string.h>

class CName
{
   char m_szFirst[256];
   char m_szLast[256];
public:
   void SetName(char* pszFirst, char* pszLast)
   {
      strcpy(m_szFirst, pszFirst);
      strcpy(m_szLast, pszLast);
   }
};

int main()
{
   char* pCharArray = new char[256];  // Allocate memory for the array
   strcpy(pCharArray, "Array of characters");
   delete [] pCharArray;              // Deallocate memory for the array
   pCharArray = NULL;

   CName* pName = new CName;          // Allocate memory for the object
   pName->SetName("Firstname", "Lastname");
   delete pName;                      // Deallocate memory for the object
   pName = NULL;
}

The new operator cannot be used to allocate a function, but it can be used to allocate pointers to functions. The following example allocates and then frees an array of seven pointers to functions that return integers.

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

If you use the operator new without any extra arguments, and compile with the /GX, /EHa, or /EHs 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. For example:

// expre_new_Operator2.cpp
// C2660 expected
class A {
public:
    A(int) { throw "Fail!"; }
};
void F(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.  Since
        // ::operator delete(void*, char*, int) has not been implemented,
        // memory will be leaked when the deallocation cannot occur.

        A* pa2 = new(__FILE__, __LINE__) A(20);
    } catch (...) {
    }
}

int main()
{
}

The following example allocates and then frees a two-dimensional array of characters of size dim by 10. When allocating a multidimensional array, all dimensions except the first must be constant expressions that evaluate to positive values; the leftmost array dimension can be any expression that evaluates to a positive value. When allocating an array using the new operator, the first dimension can be zero — the new operator returns a unique pointer.

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

The type-name cannot contain const, volatile, class declarations, or enumeration declarations. Therefore, the following expression is illegal:

volatile char *vch = new volatile char[20];

The new operator does not allocate reference types because they are not objects.

See Also

Expressions with Unary Operators | C++ Keywords | Lifetime of Objects Allocated with new | Initializing Objects Allocated with new | How new Works | The operator New Function

Show:
© 2014 Microsoft