轉:malloc VS new, free VS delete
記憶體操作一直以來都讓程式設計師吃足苦頭,我們也來簡單看看.
在C語言中,我們申請記憶體時先包含malloc.h標頭檔案,使用函式malloc申請,C++中依然保留了該方式,新增加了種方式new ,該運算子不僅能為基本型別變數申請空間,能給物件申請空間,對應的釋放操作則為delete,我們來看個簡單的
[@more@]// 2006-09-13-3.cpp : 定義控制檯應用程式的入口點。
// 動態開闢記憶體地址,該處要注意,要把開闢的空間釋放(free)
// C++中獨有的new,delete方式建立與刪除記憶體空間
// array = new int[arraysize],對於陣列,則需要delete[]
// 轉載請註明出處
#include
#include
using namespace std;
void main(void)
{
int arraysize;
int *array;
cout< cin>>arraysize;
array = (int*)malloc(arraysize*sizeof(int));
// array = new int[arraysize]; //這種方式只能在C++中使用,C不行
for(int i=0;i
for(int i=0;i
//如果刪除陣列則要加[],非陣列只需要delete data
//delete[] array;
cin.get();
cin.get();
}
該例中我們可以看到,兩種方式產生的效果是完全一樣的,他們到底有什麼區別呢?
我們都知道C++中引入了物件的概念,他們最大的區別就是 new ,delete 時,將會呼叫物件的構造與解構函式,new 是在malloc的基礎上擴充套件延長,之所以保留molloc只是為了相容以前的C程式,在C++中我們推薦使用new,delete
// 出處
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220284/viewspace-1023985/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- malloc/free 和 new /delete 的區別 (轉)delete
- C malloc() free(), C++ new() delete()C++delete
- C++之new、delete 與malloc、free的異同C++delete
- malloc free與new delete的區別和聯絡delete
- new/delete 和malloc/free 的區別一般彙總delete
- SQL – TRUNCATE vs DELETESQLdelete
- single vs new
- 從free(p)到delete[]p (轉)delete
- new 和 malloc 的區別
- new和malloc的區別
- C語言中malloc與freeC語言
- vsftpdfrequentlyaskedquestions(轉)FTP
- new 和 malloc 的區別 及使用
- new和malloc的地址分配問題
- 記憶體(new delete )記憶體delete
- array new 與 array deletedelete
- VMware vSphere:What's New V5.1培訓
- Delete indexes to free database.deleteIndexDatabase
- 轉multicast vs broadcastAST
- CVS 簡介(轉)
- CVS教學(轉)
- glibc 2.23 原始碼分析 | malloc & free原始碼
- VS+opengl 環境安裝,freeglut和glew方式
- malloc和new的區別,new和operator new的區別,分配器介紹
- NOSQL資料庫大比拼:Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBaseSQL資料庫MongoDBRedis
- CVS使用簡介(轉)
- Windows XP VS Linux (轉)WindowsLinux
- VSFTPD的基本配置(轉)FTP
- RDBMS VS XML VS NoSQLXMLSQL
- Axum vs Actix vs Rocket
- vsftpd-1.1.3配製檔案vsftpd.conf(轉)FTP
- TensorFlowVSTensorFlowMobileVSTensorFlowLite
- vs 2017 vs code
- EncodedvsLiteral,RPCvsDocumentRPC
- 細說new和malloc的十大區別
- 記憶體分配詳解 malloc, new, HeapAlloc, VirtualAlloc,GlobalAlloc記憶體
- C++中new與malloc的10點區別C++
- 轉貼:Spring vs. EJBSpring