The function operator new is responsible for allocating memory when a new expression is invoked. The new operator can either be a globally defined function or a static member function of a class. It is possible to overload the global operators, new and delete. Later on in this chapter, we will see that this can be useful when analyzing memory usage. Here is how to do it:
auto operator new(size_t size) -> void* { void* p = std::malloc(size); std::cout << "allocated " << size << " byte(s)" << '\n'; return p; } auto operator delete(void* p) noexcept -> void { std::cout << "deleted memory\n"; return std::free(p); }
We can verify that our overloaded operators are actually being used when creating and deleting a