The new
operator and operator new
are not the same thing.
The new
operator calls an operator new
function to allocate memory, and then, depending on the type allocated and the syntax used, initializes or calls a constructor on the allocated memory. In other words, operator new
forms only a part of the operation of the new
operator.
operator new
is the function called to allocate memory by the new
operator. There's a default implementation of operator new
which can be replaced, which is not the same thing as overloading. operator new
can also be implemented for a particular type to handle allocations only of objects of that type, or operator new
can be overloaded and the overload can be selected by using the placement new form of the new
operator.
The default implementations of operator new
can be replaced by defining functions with the following signatures:
void *operator new(std::size_t size);
void *operator new(std::size_t size, const std::nothrow_t&);
void *operator new[](std::size_t size);
void *operator new[](std::size_t size, const std::nothrow_t&);
When you provide a replacement or overload for operator new
you should provide corresponding operator delete
functions:
void operator delete(void* ptr) noexcept;
void operator delete(void* ptr, const std::nothrow_t&) noexcept;
void operator delete[](void* ptr) noexcept;
void operator delete[](void* ptr, const std::nothrow_t&) noexcept;
To provide an overload of operator new
for use with the placement form of the new
operator you can add additional arguments (the nothrow versions of operator new
and operator delete
do this).
struct my_type {};
void *operator new(std::size_t size, const my_type&);
void operator delete(void *ptr, const my_type&);
new (my_type()) int(10); // allocate an int using the operator new that takes a my_type object
There is no 'placement delete' form of the delete
operator. The overload of operator delete
is provided because if an error occurs during the initialization/construction of the memory (e.g., the constructor called by the new
operator after operator new
has been called) the corresponding operator delete
is called if it exists before re-throwing the exception. Otherwise operator delete
is not called and the memory leaks when the exception is thrown.