C++基础06-类与对象之new和malloc
1、C和C++動態分配內存區別:
????????? 在C語言中是利用庫函數malloc和free來分配和撤銷內存空間的。
????????? C++提供了較簡便而功能較強的運算符new和delete來取代 malloc和free函數。
new和delete是運算符,不是函數,因此執行效率高。
2、new和delete的用法
<1>用法示例:
new int;
//開辟?個存放整數的存儲空間,返回?個指向該存儲空間的地址(即指針)
new int(100);
//開辟?個存放整數的空間,并指定該整數的初值為100,返回?個指向該存儲空間的地址
new char[10];
//開辟?個存放字符數組(包括10個元素)的空間,返回?元素的地址
new int[5][4];
//開辟?個存放?維整型數組(??為5*4)的空間,返回?元素的地址
float *p=new float (3.14159);
//開辟?個存放單精度數的空間,并指定該實數的初值為//3.14159,將返回的該空間的地址賦給指針變量p
?
用new分配數組空間時不能指定初值。如果由于內存不足等原因而無法正常分配空間,則new會返回一個空指針NULL,用戶可以根據該指針的值判斷分 配空間是否成功。
<2>用法總結:
new運算符動態分配堆內存
使用形式: 指針變量=new 類型(常量);
?????????????????? 指針變量=new 類型[表達式];
作用:從堆分配一塊類型大小的存儲空間,返回首地址
其中:‘常量’是初始化值,可以省略。創建數組對象時,不能為對象指定初始值。
delete運算符釋放已經分配的內存空間
使用形式:delete 指針變量;
????????????????? delete [] 指針變量;
其中 ‘指針變量’必須是一個new返回的指針
3、new和malloc區別
malloc不會調用類的構造函數,而new會調用類的構造函數
Free不會調用類的析構函數,而delete會調用類的析構函數
#if 1 #include<iostream> #include<stdio.h> using namespace std; //1 //malloc free 是函數,標準庫 stdlib.h //new malloc是運算符 沒有進棧出棧等操作 //2 //new 在堆上初始化對象時,會觸發對象的構造函數 malloc不能 //delete 可以觸發對象的析構函數 free不能void c_test01() {int* p = (int *)malloc(sizeof(int));if (p != NULL)*p = 2;if (p != NULL) {free(p);//等價delete p;p = NULL;}int *array_p = (int *)malloc(sizeof(int) * 10);if (array_p != NULL) {for (int i = 0; i < 10; i++){array_p[i] = i;}}for (int i = 0; i < 10; i++){printf("%d ", array_p[i]);}cout << endl;if (array_p != NULL) {free(array_p);array_p = NULL;} }void cpp_test01() {int *p = new int;if (p != NULL)*p = 2;if (p != NULL) {delete p;//等價free(p);p = NULL;}int *array = new int[10]; //意思是開辟一個4*10字節空間//int *array = new int(10); 意思是開辟一個4字節空間,賦值為10if (array != NULL) {for (int i = 0; i < 10; i++){array[i] = i;}}for (int i = 0; i < 10; i++){printf("%d ", array[i]);}if (array != NULL) {delete[] array; array = NULL;} } class Test { public:Test(){cout << "Test()" << endl;m_a = 0;m_b = 0;}Test(int a, int b){cout << "Test(int, int)" << endl;m_a = a;m_b = b;}void printT(){cout << "printT:" << m_a << "," << m_b << endl;}~Test(){cout << "~Test()" << endl;} private:int m_a;int m_b; }; void c_test02() {Test *tp = (Test *)malloc(sizeof(Test));tp->printT();if (tp != NULL) {free(tp);tp = NULL;} }void cpp_test02() {Test *tp = new Test; //等價于Test *tp = new Test();//Test *tp = new Test(10, 20); //觸發有參構造tp->printT();if (tp != NULL) {delete tp;tp = NULL;} } void test01() {c_test01();cout << "----------------" << endl;cpp_test01(); } /* 0 1 2 3 4 5 6 7 8 9 ---------------- 0 1 2 3 4 5 6 7 8 9 */ void test02() {c_test02();cout << "----------------" << endl;cpp_test02(); } /* printT:-842150451,-842150451 ---------------- Test() printT:0,0 ~Test() */ int main() {test01();//test02(); }#endif?
總結
以上是生活随笔為你收集整理的C++基础06-类与对象之new和malloc的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python内置输入函数_python内
- 下一篇: Windows 系统下.sh文件的运行