I want to overload 'new' operator. I made one Header file where macro for 'new' is declared.
HeaderNew.h
#ifndef MYNEW_H
#define MYNEW_H
#define new new(__FILE__, __LINE__)
void* operator new(std::size_t size, const char* file, unsigned int line);
#endif
myNew.cpp
#include<iostream>
#include<malloc.h>
#include<cstddef>
#include "mynew.h"
using namespace std;
#undef new
void* operator new(std::size_t size, const char* file, unsigned int line){
void *ptr = malloc(size);
cout << "This is overloaded new." << endl;
cout << "File : " << file << endl;
cout << "Line : " << line << endl;
cout << "Size : " << size << endl;
return ptr;
}
test.cpp
#include <iostream>
#include "mynew.h"
using namespace std;
int main()
{
int * ptr1 = new int;
cout << "Address : " << ptr1 << endl;
//delete ptr1;
return 0;
}
Here, I want to know the file name and line number of 'new' operator used in test.cpp . But i got a error as mentioned below.
error : declaration of ‘operator new’ as non-function in #define new new(FILE, LINE)
Can anyone tell me the reason for this error & its appropriate solution. Thanks in advance..:)
operator newand what is colloquially known as thenewoperator, the latter is a keyword built in the language and cannot (shouldn't) be redefined. Thenewoperator callsoperator newto allocate first the memory, then invokes the constructor of the passed object.void* operator new(__FILE__, __LINE__)(std::size_t size, const char* file, unsigned int line);?new?operator new, not the keywordnew. It seems the OP is re-defining a keyword:#define new new(__FILE__, __LINE__)which seems a sure recipe for disasternewcalls with his/her overloaded version that takes the file and line number. It's not portable, but in practice it will probably work, and it's not what the error is about. Apart from being a keyword and not a function, this is the same principle used byassert.