c++ 動態(tài)內(nèi)存分配相關(guān)總結(jié)
更新時間:2021年02月25日 16:55:05 作者:流星斬月
這篇文章主要介紹了c++ 動態(tài)內(nèi)存分配相關(guān)的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)和使用c++,感興趣的朋友可以了解下
下面隨筆是關(guān)于c++動態(tài)內(nèi)存分配。
動態(tài)申請內(nèi)存操作符 new
- new 類型名T(初始化參數(shù)列表)
- 功能:在程序執(zhí)行期間,申請用于存放T類型對象的內(nèi)存空間,并依初值列表賦以初值。
- 結(jié)果值:成功:T類型的指針,指向新分配的內(nèi)存;失?。簰伋霎惓?。
釋放內(nèi)存操作符delete
- delete 指針p
- 功能:釋放指針p所指向的內(nèi)存。p必須是new操作的返回值。
//例1 動態(tài)創(chuàng)建對象舉例 #include <iostream> using namespace std; class Point { public: Point() : x(0), y(0) { cout<<"Default Constructor called."<<endl; } Point(int x, int y) : x(x), y(y) { cout<< "Constructor called."<<endl; } ~Point() { cout<<"Destructor called."<<endl; } int getX() const { return x; } int getY() const { return y; } void move(int newX, int newY) { x = newX; y = newY; } private: int x, y; }; int main() { cout << "Step one: " << endl; Point *ptr1 = new Point; //調(diào)用默認(rèn)構(gòu)造函數(shù) delete ptr1; //刪除對象,自動調(diào)用析構(gòu)函數(shù) cout << "Step two: " << endl; ptr1 = new Point(1,2); delete ptr1; return 0; }
運行結(jié)果: Step One: Default Constructor called. Destructor called. Step Two: Constructor called. Destructor called.
分配和釋放動態(tài)數(shù)組
- 分配:new 類型名T [ 數(shù)組長度 ]
數(shù)組長度可以是任何表達式,在運行時計算
- 釋放:delete[] 數(shù)組名p
釋放指針p所指向的數(shù)組。
p必須是用new分配得到的數(shù)組首地址。
//例2 動態(tài)創(chuàng)建對象數(shù)組舉例 #include<iostream> using namespace std; class Point { //類的聲明同例6-16,略 }; int main() { Point *ptr = new Point[2]; //創(chuàng)建對象數(shù)組 ptr[0].move(5, 10); //通過指針訪問數(shù)組元素的成員 ptr[1].move(15, 20); //通過指針訪問數(shù)組元素的成員 cout << "Deleting..." << endl; delete[] ptr; //刪除整個對象數(shù)組 return 0; }
運行結(jié)果: Default Constructor called. Default Constructor called. Deleting... Destructor called. Destructor called.
動態(tài)創(chuàng)建多維數(shù)組
new 類型名T[第1維長度][第2維長度]…;
如果內(nèi)存申請成功,new運算返回一個指向新分配內(nèi)存首地址的指針。
例如:
char (*fp)[3];
fp = new char[2][3];
//例3 動態(tài)創(chuàng)建多維數(shù)組 #include <iostream> using namespace std; int main() { int (*cp)[9][8] = new int[7][9][8]; for (int i = 0; i < 7; i++) for (int j = 0; j < 9; j++) for (int k = 0; k < 8; k++) *(*(*(cp + i) + j) + k) =(i * 100 + j * 10 + k); for (int i = 0; i < 7; i++) { for (int j = 0; j < 9; j++) { for (int k = 0; k < 8; k++) cout << cp[i][j][k] << " "; cout << endl; } cout << endl; } delete[] cp; return 0; }
以上就是c++ 動態(tài)內(nèi)存分配相關(guān)總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于c++ 動態(tài)內(nèi)存分配的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Linux網(wǎng)絡(luò)編程之socket文件傳輸示例
這篇文章主要介紹了Linux網(wǎng)絡(luò)編程之socket文件傳輸示例,對于基于Linux平臺的C程序員來說有一定的借鑒價值,需要的朋友可以參考下2014-08-08