Share via


new operator (STL Samples)

Illustrates how to use operator new in <new>.

void *operator new(
   size_t n
)
void *operator new(
   size_t n,
   const nothrow&
)
void *operator new[](
   size_t n
);

Remarks

Note

The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

The first new operator will attempt to allocate memory and if it fails, will throw an exception. The new second operator accepts a second parameter of type nothrow. This parameter indicates that if the allocation fails, it should return NULL and not throw an exception. The new third operator will allocate memory for an array of that type and if it fails, will throw an exception.

Example

// newop.cpp
// compile with: /EHsc
//
// Functions:
//   void *operator new(size_t n)
//   void *operator new(size_t n, const nothrow&)
//   void *operator new[](size_t n);

#include <new>
#include <iostream>
using namespace std;

class BigClass {
public:
   BigClass() {};
   ~BigClass(){}

#ifdef _WIN64
      double BigArray[0x0fffffff];
#else
      double BigArray[0x0fffffff];
#endif
};

int main() {
   try {
      BigClass * p = new BigClass;
   }

   catch( bad_alloc a) {
      const char * temp = a.what();
      cout << temp << endl;
      cout << "Threw a bad_alloc exception" << endl;
   }

   BigClass * q = new(nothrow) BigClass;

   if ( q == NULL )
      cout << "Returned a NULL pointer" << endl;

   try {
      BigClass * r[3] = {new BigClass, new BigClass, new BigClass};
   }

   catch( bad_alloc a) {
      const char * temp = a.what();
      cout << temp << endl;
      cout << "Threw a bad_alloc exception" << endl;
   }
}

Sample Output

bad allocation
Threw a bad_alloc exception
Returned a NULL pointer
bad allocation
Threw a bad_alloc exception

Requirements

Header: <new>

See Also

Concepts

Standard Template Library Samples