C++ 我怎么能让“超负荷”呢;新";操作员是否从辅助内存设备分配内存?
我正在寻找从辅助内存设备而不是从默认堆分配内存的语法C++ 我怎么能让“超负荷”呢;新";操作员是否从辅助内存设备分配内存?,c++,memory-management,c++-faq,C++,Memory Management,C++ Faq,我正在寻找从辅助内存设备而不是从默认堆分配内存的语法 我如何实现它?默认情况下,使用malloc()将从堆中获取它。。。肯定还有别的办法 您必须构建或调整自己的堆管理器,并重载new和delete,以及new[]和delete[]。使用特殊内存初始化堆管理器。\include #include <new> void* operator new(std::size_t size) throw(std::bad_alloc) { while (true) { void* r
我如何实现它?默认情况下,使用
malloc()
将从堆中获取它。。。肯定还有别的办法 您必须构建或调整自己的堆管理器,并重载new
和delete
,以及new[]
和delete[]
。使用特殊内存初始化堆管理器。\include
#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
}
void*运算符新建(std::size\u t size)抛出(std::bad\u alloc){
while(true){
void*result=从某个资源分配资源(大小);
if(result)返回结果;
std::new_handler nh=std::set_new_handler(0);
std::set_new_handler(nh);//将其放回
//我知道这很笨拙,但是没有可移植的方式来查询当前的
//无需更换新的处理程序
//如果不想,您不必使用新的处理程序
如果(!nh)抛出std::bad_alloc();
nh();
}
}
void操作符delete(void*ptr)throw(){
if(ptr){//if您的释放函数不能接收空指针
//那你必须先检查一下
//如果您不确定,不管怎样先检查总是正确的
从某个或其他来源(ptr)解除分配;
}
}
void*运算符新[](标准::大小\u t大小)抛出(标准::错误\u分配){
返回运算符new(size);//延迟到非数组版本
}
void操作符delete[](void*ptr)throw(){
运算符删除(ptr);//遵从非数组版本
}
那么,您如何与其他设备通信?您的平台是否为其提供了API?C++没有任何标准的方法来做这件事,它是平台依赖的。谢谢罗杰,请你给我做的确切功能:分配一个来源(大小);不,他不能。如果你看到我的评论,这完全取决于你的平台。C++在机器上不说一个字,它是在运行的。那些分配和释放函数的地方是你与你的“次要存储器设备”通信的地方。它们到底是什么取决于你在做什么。