C/C++中的内存管理小结

2020-05-12 11:57:18王冬梅

3.1 内置类型的内存分配与释放

new和malloc一样会在堆上开辟空间同时需要我们手动进行内存的释放,但是new的写法更加简单易于理解同时我们还可以对单个申请的变量进行初始化。

举个栗子帮助理解

#include <iostream>
using namespace std;
int main(){
 int* a = new int;//等同于int* a = (int*)malloc(sizeof(int));
 int* b = new int[10];//等同于int* b = (int*)malloc(sizeof(int) * 10);
 int* c = new int(10);//new还可以进行内置类型的初始化
 cout << *c << endl;
  
 delete a;//等同于free(a);
 delete[] b;//等同于free(b);(对于多个变量的空间释放要用delete[])
 delete c;//等同于free(c);
 
 return 0;              
}

3.2 自定义类型的内存分配和释放

针对自定义类型的内存分配和释放,new不但可以在分配内存的时候手动调用指定的构造函数还会在分配多个对象的空间时自动调用默认构造函数,delete也会自动调用析构函数,而malloc和free却做不到这一点。因此可以理解为malloc和free分配出来的只不过是一个和类一样大小的空间,并不能称作是一个对象,而new和delete分配出来的才能被成为对象。

#include <iostream>                 
#include <stdlib.h> 
using namespace std;              
class Stu{                          
public:        
 Stu(){         
   cout << "default building" << endl;
  }
        
  Stu(int num, string name):_num(num), _name(name){        
   cout << "custom building" << endl;
  }
         
  ~Stu(){                
   cout << "destroying" << endl;
  }
private:
 int _num;
 string _name;    
};
       
int main(){     
 cout << "malloc:" << endl;
 Stu* a = (Stu*)malloc(sizeof(Stu));
 cout << "new:" << endl;
 Stu* b = new Stu(1, "张三");
 cout << "malloc:" << endl;
 Stu* c = (Stu*)malloc(sizeof(Stu) * 5);
 cout << "new:" << endl;
 Stu* d = new Stu[5];
 cout << "free:" << endl;
 free(a);
 cout << "delete:" << endl;
 delete b;
 cout << "free:" << endl;
 free(c);
 cout << "delete:" << endl;
 delete[] d;
}       

运行结果:

 malloc:
 new:
 custom building
 malloc:
 new:
 default building
 default building
 default building
 default building
 default building
 free:
 delete:
 destroying
 free:
 delete:
 destroying
 destroying
 destroying
 destroying
 destroying

3.3 new和delete的实现原理

new和delete在C++中其实被定义为两个运算符,我们在使用这两个运算符的时候它会在底层调用全局函数operator new和operator delete。