Category
Operators, C++-Specific Keywords
Syntax
void *operator new(std::size_t size) throw(std::bad_alloc); void *operator new(std::size_t size, const std::nothrow_t &) throw(); void *operator new[](std::size_t size) throw(std::bad_alloc); void *operator new[](std::size_t size, const std::nothrow_t &) throw(); void *operator new(std::size_t size, void *ptr) throw(); // Placement form void *operator new[](std::size_t size, void *ptr) throw(); // Placement form
Description
The new operators offer dynamic storage allocation, similar but superior to the standard library function malloc. These allocation functions attempt to allocate size bytes of storage. If successful, new returns a pointer to the allocated memory. If the allocation fails, the new operator will call the new_handler function. The default behavior of new_handler is to throw an exception of type bad_alloc. If you do not want an exception to be thrown, use the nothrow version of operator new. The nothrow versions return a null pointer result on failure, instead of throwing an exception.
The default placement forms of operator new are reserved and cannot be redefined. You can, however, overload the placement form with a different signature (i.e. one having a different number, or different type of arguments). The default placement forms accept a pointer of type void, and perform no action other than to return that pointer, unchanged. This can be useful when you want to allocate an object at a known address. Using the placement form of new can be tricky, as you must remember to explicitly call the destructor for your object, and then free the pre-allocated memory buffer. Do not call the delete operator on an object allocated with the placement new operator.
A request for non-array allocation uses the appropriate operator new() function. Any request for array allocation will call the appropriate operator new[]() function. Remember to use the array form of operator delete[](), when deallocating an array created with operator new[]().
Example of Operator new with Nothrow
#include <new> int main(int argc, char* argv[]) { int *pn; // nothrow version returns null pointer rather than throwing a // bad_alloc exception. pn = new(nothrow) int[5000000]; if(pn != NULL) { // Allocation succeded. } return 0; }
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|