簡體   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