Freigeben über


new operator (STL Samples)

Veranschaulicht, wie Operator neu in <new>verwendet.

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

Hinweise

HinweisHinweis

Die Klasse/Parameternamen im Prototyp stimmen nicht mit der Version in der Headerdatei ab.Einige wurden geändert, um die Lesbarkeit zu verbessern.

Der erste neu-Operator versucht Speicher belegen und wenn sie fehlschlägt, wird eine Ausnahme ausgelöst.Der Operator neu zweite nimmt einen zweiten Parameter vom Typ nothrow.Dieser Parameter gibt an, dass die Belegung fehlschlägt, wenn er NULL zurückgeben und keine Ausnahme auslösen soll.Der dritte Operator neu belegt Speicher für ein Array dieses Typs und wenn sie fehlschlägt, wird eine Ausnahme ausgelöst.

Beispiel

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

Beispielausgabe

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

Anforderungen

Header: <new>

Siehe auch

Konzepte

Standardvorlagenbibliotheks-Beispiele