new有三種使用方式:plain new,nothrow new和placement new。
(1)plain new顧名思義就是普通的new,就是我們慣常使用的new。在C++中是這樣定義的:
void* operator new(std::size_t) throw(std::bad_alloc);
void operator delete(void *) throw();
提示:plain new在分配失敗的情況下,拋出異常std::bad_alloc而不是返回NULL,因此通過判斷傳回值是否為NULL是徒勞的。
(2)nothrow new是不拋出異常的運算子new的形式。nothrow new在失敗時,返回NULL。定義如下:
void * operator new(std::size_t,const std::nothrow_t&) throw();
void operator delete(void*) throw();
(3)placement new意即“放置”,這種new允許在一塊已經分配成功的記憶體上重新構造對象或對象數組。placement new不用擔心記憶體配置失敗,因為它根本不分配記憶體,它做的唯一一件事情就是調用對象的建構函式。定義如下:
void* operator new(size_t,void*);
void operator delete(void*,void*);
提示1:palcement new的主要用途就是反覆使用一塊較大的動態分配的記憶體來構造不同類型的對象或者他們的數組。
提示2:placement new構造起來的對象或其數組,要顯示的調用他們的解構函式來銷毀,千萬不要使用delete。
char* p = new(nothrow) char[100];
long *q1 = new(p) long(100);
int *q2 = new(p) int[100/sizeof(int)];
char* p = new(nothrow) char[100];
long *q1 = new(p) long(100);
int *q2 = new(p) int[100/sizeof(int)];
這三句的意思是先用nothrow new申請char[100]空間,再在這片空間上申請一個long類型的空間存放100,然後是int型的數組
更多閱讀連結
http://www.scs.stanford.edu/~dm/home/papers/c++-new.html
http://eli.thegreenplace.net/2011/02/17/the-many-faces-of-operator-new-in-c/ !!!!!!!
http://en.wikipedia.org/wiki/Placement_syntax
http://blog.csdn.net/huyiyang2010/article/details/5984987
http://www.gotw.ca/publications/mill15.htm
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=170