引言:

我们往往使用new delete对象,这个过程被编译器藏得很深,但是这个过程具体是什么?和C语言的malloc、free有什么样的区别和联系呢?那就先看看下面这个点类的设计,本文将通过这个代码进行new和delete对象的步骤的深入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
class Point
{
public:
Point(){}
Point(int r, int c)
{
row = r;
col = c;
}
~Point();
private:
int row; //行
int col; //列
};

int main()
{
//new p过程
Point* p = new Point(10, 20);

//delete p过程
delete p;
}

(一)new对象过程

1
2
3
4
5
6
7
8
9
//new p过程
Point* p = new Point(10, 20);

/*
* 1.申请空间:Point* p = (Ponit*)malloc(sizeof(Point));
* 2.构建对象: //定位new
* new(s) Pointer(10, 20);
* 3.返回堆空间首地址
*/

(二)delete对象过程

1
2
3
4
5
6
7
8
//delete p过程
delete p;

/*
* 1.调用析构函数:p->~Point();
* 2.释放内存空间:free(p); p = NULL;
*/

注意:

  • C++中 分配了空间不一定就有对象(对象还没有创建出来)
  • 使用定位new开辟的空间,需要手动调用对象的析构函数,以及手动释放free该空间