How might I overload the “new” operator to allocate memory from a secondary memory device?

我与影子孤独终老i 提交于 2020-01-20 04:22:27

问题


I am looking for a syntax to allocate memory from a secondary memory device and not from the default heap.

How can i implement it? Using malloc() would by default take it from heap... Surely there must be another way!


回答1:


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



回答2:


You'd have to build or adapt your own heap manager, and overload new and delete, as well as new[] and delete[]. Initialize the heap manager with the special memory.



来源:https://stackoverflow.com/questions/1898920/how-might-i-overload-the-new-operator-to-allocate-memory-from-a-secondary-memo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!