C C 之動態記憶體分配比較

2021-08-26 07:01:26 字數 2442 閱讀 4163

1、c malloc 和 free vs c++ new 和delete:

c 語言的malloc() 和free() 並不會呼叫析構函式和建構函式。c++的 new 和 delete 操作符 是 "類意識" ,並且當呼叫new的時候會呼叫類的建構函式和當delete 呼叫的時候會呼叫析構函式。

下面乙個例子

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include using namespace std; class ss ; ss::ss() ss::~ss() int _tmain(int argc, _tchar* argv)

執行結果:

如圖一注意:混合用malloc 和delete或者混合用new 和free 是不正確的。c++的new和delete是c++用構造器分配記憶體,用析構函式清除使用過的記憶體。

new/delete 優點:

2、c 的動態記憶體分配:

看如下例子malloctest.cpp

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include using namespace std; typedef struct sss; int _tmain(int argc, _tchar* argv) for(jj=0; jj < 5; jj++) free(s1); free(str1); free(str2); }

結果:圖二注意:

3、c++ 動態記憶體分配:

使用 "new" 和 "delete"

如下示例:檔案: allocnewtest.cpp

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include using namespace std; class ccc

注意:

結果如圖:

圖四4、c 函式返回乙個指標vs c++函式返回的是乙個副本:

c 函式返回乙個指標

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include #include #include using namespace std; char *fnconvert(int _ii) int _tmain(int argc, _tchar* argv)

執行結果:

圖五c++ 函式返回的是乙個副本:

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include #include #include using namespace std; string fnconvert(int _ii) int _tmain(int argc, _tchar* argv)

執行結果

圖六注意:c++的stl string類的賦值建構函式是被用來返回乙個值的副本,也就是當我們離開了函式的時候,變數 "ost",不在作用域了,但是所賦複製的內容是有效的。不要返回"return ost.str().c_str()" 作為他的指標,他是不在作用域的內一旦程式離開了函式,並且資料會丟失。

5、c++ 動態記憶體分配的異常處理:

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include #include #include using namespace std; int _tmain(int argc, _tchar* argv) } catch ( bad_alloc &memmoryallocationexception ) catch(...) return 0; }

執行:6、c++ virtual destructors

// memory.cpp : 定義控制台應用程式的入口點。 //2011/10/13 by wallwind #include "stdafx.h" #include #include #include using namespace std; class base ; virtual ~base() }; class derived : public base ; ~derived() }; int _tmain(int argc, _tchar* argv)

執行結果:

圖七注意:

C C 動態記憶體分配

int p null c語言寫法 等價於數字0 p int malloc sizeof int if p null 例2 char point null point char malloc sizeof char if point null 例3 int p int malloc sizeof in...

C C 的動態記憶體分配

記憶體分配方式有三種 從靜態儲存區分配 內存在編譯的時候已經分配好,這塊內存在程式的整個執行期間都存在 例 全域性變數 static變數 在棧上建立 區域性變數在棧上建立,函式執行結束時這些儲存單元自動被釋放。效率高,但容量有限。從堆上分配 動態記憶體分配。程式設計師用時自己申請和釋放,使用靈活,但...

C之動態記憶體分配

在編寫程式時,通常並不知道需要處理的資料量,或者難以評估所需處理資料量的變動程度。在這種情況下,要達到有效的資源利用,必須在執行時動態地分配所需記憶體,並在使用完畢後盡早釋放不需要的記憶體,這就是動態記憶體管理原理。參考文章 1 c語言動態記憶體管理和動態記憶體分配 標準庫stdlib.h提供以下四...