繁体   English   中英

C ++中新增的运算符重载

[英]Overloading of operator new in C++

我想重载“新”运算符。 我制作了一个Header文件,其中声明了“ new”的宏。

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;
}

测试文件

#include <iostream>
#include "mynew.h"
using namespace std;

int main()
{
   int * ptr1 = new int;
   cout << "Address : " << ptr1 << endl;
   //delete ptr1;
   return 0;
}

在这里,我想知道test.cpp中使用的'new'运算符的文件名和行号。 但是我有一个错误,如下所述。

错误:在#define new new( FILELINE )中将'operator new'声明为无效

谁能告诉我此错误的原因及其适当的解决方案。 提前致谢..:)

定义之后,# #define的工作随处可见。

这意味着:

#define  new    new(__FILE__, __LINE__)
void* operator new(std::size_t size, const char* file, unsigned int line);

被预处理器更改为:

void* operator new(__FILE__, __LINE__)(std::size_t size, const char* file, unsigned int line);

看到问题了吗?

在声明operator new之后,尝试移动#define行。

另外,请注意,此技巧并不完全可靠-例如,它将破坏您拥有的任何其他operator new声明,或放置new调用(包括在使用放置new任何标准标头中); “ placement new ”是new operator new的内置重载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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