C++ new 和Placement New 以及nothrow new

來源:互聯網
上載者:User

 

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

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.