Pointers/Memory Allocation   «Prev 

operators new delete

The operators new and delete access heap storage and are built into the language.
They are to be preferred to the older C library functions malloc() and free(), which do not automatically understand the C++ types they are working with. Heap allocation that fails will result in either an allocation exception being thrown or a return value of 0 as a pointer expression indicating failure. Assertions or catches can be used as a postcondition to test whether heap allocation succeeded. These errors are system-dependent and should be routinely tested for at runtime.

void* operator new[] (std::size_t size) throw (std::bad_alloc);
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_constant) throw();
void* operator new[] (std::size_t size, void* ptr) throw();

Allocate storage space for array

The first version allocates size bytes of storage space, aligned to represent an array object of that size (or less, if the implementation uses array overhead), and returns a non-null pointer to the first byte of this block. On failure, it throws a bad_alloc exception. The second version is the nothrow version. It does the same as the first version, except that on failure it turns a null pointer instead of throwing an exception.
The third version is the placement version, that does not allocate memory - it simply returns ptr. Notice though that the constructor for the object will still be called.
Global dynamic storage operator functions are special in the standard library:
  1. All three versions of operator new[] are declared in the global namespace, not in the std namespace.
  2. The first and second versions are implicitly declared in every translation unit of a C++ program: The header <new> does not need to be included for them to be present.
  3. The first and second versions are also replaceable: A program may provide its own definition, that replaces the default one, to produce the result described above.