<new>

The <new> header declares types and functions related to dynamic memory management. (See Chapter 3 for more information about the new and delete expressions, including placement new and delete, and the operator new and operator delete functions.) Most programs do not need to use <new>. The header is typically used by libraries and programs that implement their own operator new and operator delete functions or otherwise provide custom management of dynamic memory.

If a source file uses the standard new and delete expressions, it does not need to #include <new>. You can also use the pointer placement new without including this header. In order to use the nothrow placement new, or catch bad_alloc, you must include this header.

Most programs do not call the operators directly, but instead use new and delete expressions, and the compiler generates calls using the appropriate operators. Library implementors sometimes make direct calls to the operators, especially to allocate uninitialized memory. See <memory> earlier in this chapter for examples.

Some specialized applications might implement the global operator new and operator delete functions or provide additional overloaded operators for specialized circumstances, such as allocating memory that is shared across process boundaries. If you write your own operator new, you should obey the following guidelines:

Example 13-32 shows a trivial implementation of the global operator new and operator delete functions.

Example 13-32. Implementing operator new and operator delete with malloc and free

#include <cstdlib>
#include <new>
   
void* operator new(std::size_t size) throw(std::bad_alloc)
{
  void* ptr = std::malloc(size);
  if (ptr == 0)
    throw std::bad_alloc(  );
  return ptr;
}
   
void* operator new(std::size_t size, const std::nothrow_t&)
throw(  )
{
  return std::malloc(size);
}
   
void* operator new[](std::size_t size) throw(std::bad_alloc)
{
  return operator new(size);
}
   
void* operator new[](std::size_t size, const std::nothrow_t&)
throw(  )
{
  return operator new(size, std::nothrow);
}
   
void operator delete(void* ptr) throw(  )
{
  std::free(ptr);
}
   
void operator delete(void* ptr, const std::nothrow_t&)
throw(  )
{
  std::free(ptr);
}
   
void operator delete[](void* ptr) throw(  )
{
  operator delete(ptr);
}
   
void operator delete[](void* ptr, const std::nothrow_t&)
throw(  )
{
  operator delete(ptr);
}