一、概念
在C++中new的三种用法包括:plain new, nothrow new 和 placement new。
plain new 就是我们最常使用的new的方式,在C++中的定义如下:
1 void* operator new(std::size_t) throw(std::bad_alloc);
2 void operator delete( void *) throw();
plain new在分配失败的情况下,抛出异常std::bad_alloc而不是返回NULL,因此通过判断返回值是否为NULL是徒劳的。
nothrow new 是不抛出异常的运算符new的形式。nothrow new在失败时,返回NULL。定义如下:
1 void * operator new(std::size_t, const std::nothrow_t&) throw();
2 void operator delete(void*) throw();
placement new 意即“放置”,这种new允许在一块已经分配成功的内存上重新构造对象或对象数组。placement new不用担心内存分配失败,因为它根本不分配内存,它做的唯一一件事情就是调用对象的构造函数。定义如下:
1 void* operator new(size_t, void*);
2 void operator delete(void*, void*);
palcement new 的主要用途就是反复使用一