<new>中定义了几种函数,这些函数负责动态内存的分配;
常量:
nothrow : nothrow常量当operator new申请一个内存失败的时候,它会进行如下的处理步骤: 1、如果存在客户指定的处理函数,则调用处理函数(new_handler),如果不存在则抛出一个异常。 2、继续申请内存分配请求。 3、判断申请内存是否成功,如果成功则返回内存指针,如果失败转向处理步骤1
例子:
#include <iostream> #include <new> void handler() { std::cout << "Memory allocation failed, terminating\n"; std::set_new_handler(nullptr); } int main() { std::set_new_handler(handler); try { while (true) { new int[100000000ul]; } } catch (const std::bad_alloc& e) { std::cout << e.what() << '\n'; } } //----------u 输出为: Memory allocation failed, terminating std::bad_alloc这个分配内存失败,然后调用客户设定的new_handler处理函数;
提示1:palcement new的主要用途就是反复使用一块较大的动态分配的内存来构造不同类型的对象或者他们的数组。
提示2:placement new构造起来的对象或其数组,要显示的调用他们的析构函数来销毁,千万不要使用delete。
// 第一种 void* operator new(std::size_t) throw(std::bad_alloc); void operator delete(void *) throw(); //第二种 void * operator new(std::size_t,const std::nothrow_t&) throw(); void operator delete(void*) throw(); //第三种 void* operator new(size_t,void*); void operator delete(void*,void*); //第三种实例 char* p = new(nothrow) char[100]; long *q1 = new(p) long(100);//在p的内存上重新构造 int *q2 = new(p) int[100/sizeof(int)];【详细文档】 1. c++中new的三种用法详细解析