new operator (STL Samples)
演示如何使用 new 运算符in <new>。
void *operator new(
size_t n
)
void *operator new(
size_t n,
const nothrow&
)
void *operator new[](
size_t n
);
备注
备注
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.
示例
// 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;
}
}
示例输出
bad allocation
Threw a bad_alloc exception
Returned a NULL pointer
bad allocation
Threw a bad_alloc exception
要求
Header: <new>