使用我的API修改新运算符

Modifying new operator using my API

本文关键字:运算符 修改 API 我的      更新时间:2023-10-16

我想使用处理器的自定义API修改工具链中的newdelete运算符。有一些内存分配问题,所以供应商说我必须这样修改它们。在工具链中,我转到名为"new"的头文件并检查了这些

void* operator new(std::size_t) throw (std::bad_alloc);
void* operator new[](std::size_t) throw (std::bad_alloc);
void operator delete(void*) throw();
void operator delete[](void*) throw();

我想做一些类似于使用的事情

using namespace std;  
if( size == 0 )  
    size = 1;  
while( true ){  
    void* pMem = my_api_malloc(size);  
    if( pMem )      
        return pMem;  
}

这是正确的方法吗?我可以在my_api_malloc是我应该使用的位置进行这样的更改吗。这是因为处理器主要使用C,并且无法识别C++运算符。

很抱歉由于缺乏声誉而无法在评论中写下这篇文章。我认为您不应该在while循环中执行malloc。如果操作系统无法为进程分配更多内存,那么无论您如何执行malloc,这都是徒劳的。此外,请注意不要使用C++中new创建的free,也不要使用malloc创建的delete

C 中的内存分配

int *a = (int*)malloc(sizeof(int)*n);
if(!a)
  return 1;

以及在C++中

try{
  int *a= new int[n];
}
catch (std::bad_alloc &e){
  // ...
}