简体   繁体   中英

Overloading of operator new in C++

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..:)

#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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM