[英]Overloading of operator new in C++
I want to overload 'new' operator. 我想重载“新”运算符。 I made one Header file where macro for 'new' is declared.
我制作了一个Header文件,其中声明了“ new”的宏。
HeaderNew.h 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 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 . 在这里,我想知道test.cpp中使用的'new'运算符的文件名和行号。 But i got a error as mentioned below.
但是我有一个错误,如下所述。
error : declaration of 'operator new' as non-function in #define new new( FILE , LINE ) 错误:在#define new new( FILE , LINE )中将'operator new'声明为无效
Can anyone tell me the reason for this error & its appropriate solution. 谁能告诉我此错误的原因及其适当的解决方案。 Thanks in advance..:)
提前致谢..:)
#define
s work everywhere after the definition. 定义之后,#
#define
的工作随处可见。
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
. 在声明
operator new
之后,尝试移动#define
行。
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
); 另外,请注意,此技巧并不完全可靠-例如,它将破坏您拥有的任何其他
operator new
声明,或放置new
调用(包括在使用放置new
任何标准标头中); "placement new
" is a built-in overload of operator new
. “ placement
new
”是new
operator new
的内置重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.