Overloading new and delete: A Few Adjustments
Explore how to overload the new and delete operators in C++ to improve memory management. Understand using macros to capture file and line info for debugging, tracking memory addresses dynamically, and handling limitations with global and special new operators. This lesson helps you identify memory leaks effectively while managing arrays and runtime memory allocation using modern C++ techniques.
We'll cover the following...
What were the not-so-nice properties in the previous lesson?
First, we only got a hint of which memory was lost. Second, we had to prepare the whole bookkeeping process of memory management at compile time. In this lesson, we aim to overcome these shortcomings.
Who is the bad guy? #
Special tasks call for special forces. Here, we can benefit from the use of a small macro for debugging purposes.
Let’s have a look at the macro #define new new(__FILE__, __LINE__)
The macro causes each new call to be mapped to the overloaded new call. This overloaded new call gets, in addition, the name of the file and the line number respectively. That’s exactly the information we need.
But what will happen if we use the macro in line 4 below?
The preprocessor substitutes all ...