C++ Operator new and delete Overloading

beginner
5 min

C++ Operator new and delete Overloading

Welcome to our comprehensive guide on C++ Operator new and delete Overloading! šŸŽÆ Let's embark on a journey to understand these crucial operators and how to use them effectively in your programming projects.

Understanding Operator new and delete

In C++, operator new and operator delete are used to dynamically allocate and deallocate memory, respectively. They are essential for managing memory in your programs.

operator new

cpp
void* operator new(size_t size);

This function is called when you use the new keyword to allocate memory. It returns a pointer to the allocated memory.

operator delete

cpp
void operator delete(void* ptr);

This function is called when you use the delete keyword to free memory. It takes a pointer to the memory that needs to be deallocated.

Overloading Operator new and delete

You can overload operator new and operator delete to customize how memory is allocated and deallocated in your program. This can be useful for tasks like tracking memory usage or integrating with memory-management libraries.

Overloading operator new

cpp
void* operator new(size_t size, const char* filename, int lineNumber);

This overloaded version of operator new accepts two additional parameters: the name of the file and the line number where the allocation occurred. This information can be useful for debugging memory leaks.

Overloading operator delete

cpp
void operator delete(void* ptr, const char* filename, int lineNumber);

This overloaded version of operator delete accepts the same additional parameters as the overloaded operator new.

Example: Overloading operator new and delete

Let's create a simple example that overloads operator new and operator delete to print the filename and line number where memory is allocated and deallocated.

cpp
#include <iostream> #include <new> class MyAllocator { public: void* operator new(size_t size) { std::cerr << "Allocating memory at " << __FILE__ << ":" << __LINE__ << std::endl; void* ptr = std::malloc(size); return ptr; } void operator delete(void* ptr) { std::cerr << "Deallocating memory at " << __FILE__ << ":" << __LINE__ << std::endl; std::free(ptr); } }; // Set global new handler std::set_new_handler(MyAllocator()); int main() { int* p = new int(42); delete p; return 0; }

In this example, we create a custom allocator called MyAllocator that overloads operator new and operator delete. When memory is allocated or deallocated, our custom allocator prints the filename and line number where the operation occurred.

šŸ“ Note: By setting the global new handler to MyAllocator, we ensure that all memory allocations in our program will use our custom allocator.

Quiz: Overloading Operator new and delete

Quick Quiz
Question 1 of 1

What does `operator new` do in C++?

Quick Quiz
Question 1 of 1

How do you set the global new handler in C++?