C++ 中 new 的3種不同的方法

來源:互聯網
上載者:User

        C++中的 new 有3中使用方式,它們是: plain new 、 nothrow new 和 placement new 。這3種形式極大地擴充了記憶體配置的靈活性。

        1. plain new

        從字面上看,這就是普通的 new ,也是我們平時使用的 new ,這裡就不多說。

        2. nothrow new

        nothrow new 就是部拋出異常的 new ,在失敗的時候返回 NULL;所以使用時不需要設定異常處理,而普通的 new 在使用失敗時是需要設定異常處理模組的。

        使用格式如下:

 

unsigned char *p = new(nothrow) unsigned char[length];<br /> if(p == NULL) cout<<"allocate failed!"<<endl;<br /> // ...<br /> delete []p;

 

 

        3.placement new

        這種 new 形式允許在一塊已經分配成功的記憶體上重新構造對象或者對象數組。使用時不必擔心失敗,因為它根本就不會分配記憶體;使用它構造起來的對象,要顯示的調用它們的解構函式,而不能使用 delete 。

        使用格式如下:

        #include <new><br />#include <iostream><br />void main()<br />{<br /> using namespace std;<br /> char *p = new(nothrow) char[4]; // nothrow new<br /> if(p == NULL)<br /> {<br /> cout<<"allocate failed!"<<endl;<br /> exit(-1);<br /> }<br /> //...<br /> long *q = new(p) long(1000); // placement new<br /> //...<br /> delete []p;<br />}

        最後說明一下,在使用後面兩種方法時,記得要加 #include <new>.

參考文獻: 林銳,韓永泉  高品質程式設計指南--C++/C語言。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.