Overloading new and delete: A Few Adjustments
In this lesson, we will refine the strategy for overloading the operators new and delete.
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?
//#include "myNew4.hpp"//#include "myNew5.hpp"#define new new(__FILE__, __LINE__)#include <iostream>#include <new>#include <string>class MyClass{float* p= new float[100];};class MyClass2{int five= 5;std::string s= "hello";};int main(){int* myInt= new int(1998);double* myDouble= new double(3.14);double* myDoubleArray= new double[2]{1.1,1.2};MyClass* myClass= new MyClass;MyClass2* myClass2= new MyClass2;delete myDouble;delete [] myDoubleArray;delete myClass;delete myClass2;dummyFunction();//getInfo();}
The preprocessor ...
Get hands-on with 1400+ tech skills courses.