如何重载"new"运算符以从辅助存储器设备分配内存?

San*_*eep 3 c++ memory-management c++-faq

我正在寻找一种语法来从辅助存储设备而不是从默认堆分配内存.

我该如何实现它?malloc()默认情况下使用将它从堆中取出...当然必须有另一种方法!

小智 11

#include <new>

void* operator new(std::size_t size) throw(std::bad_alloc) {
  while (true) {
    void* result = allocate_from_some_other_source(size);
    if (result) return result;

    std::new_handler nh = std::set_new_handler(0);
    std::set_new_handler(nh);  // put it back
    // this is clumsy, I know, but there's no portable way to query the current
    // new handler without replacing it
    // you don't have to use new handlers if you don't want to

    if (!nh) throw std::bad_alloc();
    nh();
  }
}
void operator delete(void* ptr) throw() {
  if (ptr) {  // if your deallocation function must not receive null pointers
    // then you must check first
    // checking first regardless always works correctly, if you're unsure
    deallocate_from_some_other_source(ptr);
  }
}
void* operator new[](std::size_t size) throw(std::bad_alloc) {
  return operator new(size);  // defer to non-array version
}
void operator delete[](void* ptr) throw() {
  operator delete(ptr);  // defer to non-array version
}
Run Code Online (Sandbox Code Playgroud)

  • 那些分配和解除分配功能是您与"辅助存储设备"通信的地方.它们究竟是什么将取决于你正在做什么. (5认同)
  • 不,他不能.如果你看到我的评论,那完全取决于*你的*平台.C++没有在它运行的机器上说一句话. (4认同)