Microsoft KB Archive/156808

= How to use the new operator from the Standard Library in Visual C++ =

Article ID: 156808

Article Last Modified on 7/13/2005

-

APPLIES TO

 The Standard C++ Library, when used with:  Microsoft Visual C++ 4.2 Enterprise Edition

 Microsoft Visual C++ 5.0 Enterprise Edition

 Microsoft Visual C++ 6.0 Enterprise Edition

 Microsoft Visual C++ 4.2 Professional Edition</li></ul>

 Microsoft Visual C++ 5.0 Professional Edition</li></ul>

 Microsoft Visual C++ 6.0 Professional Edition</li></ul>

 Microsoft Visual C++ 6.0 Standard Edition</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q156808

<div class="summary_section">

SUMMARY
The sample code below illustrates how to use the new operator from the Standard Library in Visual C++.

<div class="moreinformation_section">

MORE INFORMATION
The new operator will return NULL or throw an exception on failure.

Prototype
void *operator new(size_t n)  void *operator new(size_t n, const nothrow&) void *operator new[](size_t n); Note The class/parameter names in the prototype may not match the version in the header file. Some have been modified to improve readability.

Description
The first operator new will attempt to allocate memory and if it fails will throw an exception.

The second operator new 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 third operator new will allocate memory for an array of that type and if it fails will throw an exception.

Sample code
////////////////////////////////////////////////////////////////////// // // Compile options needed: /GX // // : newop.cpp // // Functions: // //   void *operator new(size_t n) // //   void *operator new(size_t n, const nothrow&) // //   void *operator new[](size_t n); // // Written by Linda Koontz // of Microsoft Product Support Services, // Copyright (c) 1996 Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////

/* Compile options needed: /GX


 * 1) include
 * 2) include

using namespace std; // std c++ libs implemented in std #endif
 * 1) if _MSC_VER > 1020  // if VC++ version is > 4.2

class BigClass { public: BigClass {}; ~BigClass{} double BigArray[99999999]; };

void 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 = new BigClass[3]; }   catch( bad_alloc a) { const char * temp = a.what; cout << temp << endl; cout << "Threw a bad_alloc exception" << endl; } }

<div class="references_section">