Reputation: 21
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..:)
Upvotes: 1
Views: 2588
Reputation: 58947
#define
s work everywhere after the definition.
Which means this:
#define new new(__FILE__, __LINE__)
void* operator new(std::size_t size, const char* file, unsigned int line);
gets changed to this, by the preprocessor:
void* operator new(__FILE__, __LINE__)(std::size_t size, const char* file, unsigned int line);
See the problem?
Try moving the #define
line after the declaration of operator new
.
Also, be aware that this trick is not entirely robust - for example, it will break any other operator new
declarations you have, or placement new
calls (including in any standard headers that use placement new
); "placement new
" is a built-in overload of operator new
.
Upvotes: 3