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