new operator (STL Sample)

The sample code below illustrates how to use the new operator.

Required Header:
<new>

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 do 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
//
// <filename> :  newop.cpp
//
// Functions:
//
//    void *operator new(size_t n)
//
//    void *operator new(size_t n, const nothrow&)
//
//    void *operator new[](size_t n);
//////////////////////////////////////////////////////////////////////

/* Compile options needed: /GX
*/

#include <new>
#include <iostream>

using namespace std;


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;
    }
}

 

Program Output is:

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