爲什麼要動態分配內存
在C++程序中,所有內存需求都是在程序執行之前通過定義所需的變量來確定的。 但是可能存在程序的內存需求只能在運行時確定的情況。 例如,當需要的內存取決於用戶輸入。 在這些情況下,程序需要動態分配內存,C ++語言將運算符new和delete合成在一起來解決動態分配內存問題.
1. new和delete的基本用法
1.1 變量申請
int* pointer = new int;
//...
delete pointer;
1.2 數組申請
int * foo;
foo = new int [5];
delete[] foo;
1.3 類對象申請
class A {...} //聲明一個類 A
A *obj = new A(); //使用 new 創建對象
delete obj; // 調用析構函數
2. new和mallc()的區別
new關鍵字是C++的一部分, 而malloc是C庫提供的函數;
當new在堆上動態分配一個對象時, 他實際做了三件事: 獲得一塊內存空間(這一步調用了mallc()函數), 調用構造函數, 返回正確的指針. 所以new調用了對象的構造函數, 而malloc()沒有.
同理使用delete的時候也是先調用類的析構函數, 然後再釋放內存空間.
3. 內存分配錯誤
3.1 直接返回異常
int main()
{
int* foo;
foo = new int [10000000000];
return 0;
}
輸出:
error:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
3.2 使用nothrow,返回空指針
#include<iostream>
int main()
{
int * foo;
foo = new (std::nothrow) int [10000000000];
if (foo == NULL)
{
std::cout<< "allocate error."<<std::endl;// error assigning memory. Take measures.
}
return 0;
}
輸出:
allocate error.
參考資料:
【C++】動態內存分配詳解(new/new[]和delete/delete[])
深入C++的new
C++ new的三種用法詳細解析
C++ new 的用法 (總結)
C++ 工程實踐(2):不要重載全局 ::operator new()