| STL Sample for the new operator FunctionID: Q156808 
 | 
The sample code below illustrates how to use the new operator from the Standard Library in Visual C++.
The new operator will return NULL or throw an exception on failure.
   <new> 
   void *operator new(size_t n)
   void *operator new(size_t n, const nothrow&)
   void *operator new[](size_t n); 
////////////////////////////////////////////////////////////////////// 
// 
// Compile options needed: /GX
// 
// <filename> :  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
*/ 
#include <new>
#include <iostream>
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;
    }
} 
bad allocation
Threw a bad_alloc exception
Returned a NULL pointer
bad allocation
Threw a bad_alloc exception 
Visual C++ Books On Line: Visual C++ Books:C/C++:Standard C++ Library
Reference. Query on [ASCII 147]operator new,[ASCII 148] or look in Help for the <new>
header file.
NOTE: The Online Help for the new header file lists the following
prototypes for the new operators demonstrated in this article:
    void *operator new(size_t n) throw(bad_alloc);
    void *operator new(size_t n, const nothrow&) throw();
    void *operator new[](size_t n) throw(bad_alloc); 
   Microsoft C++ does not support the function exception
   specification mechanism, as described in section 15.4 of the
   ANSI C++ draft. 
   void Func() throw (ProblemOne, ProblemTwo) {} 
    void Func() {
    {
    try {}
    catch (ProblemOne) {}
    catch (ProblemTwo) {}
    catch (...) { unexpected(); }
    } Additional query words: STL STLSample new
Keywords          : kbcode STLIss 
Version           : WINNT:4.2;
Platform          : NT WINDOWS 
Issue type        : kbhowto Last Reviewed: July 29, 1999