malloc/free是我们在C语言里面学习的开辟空间和释放空间的函数。
而new/delete是我们在C++里面学习的开辟空间和释放空间的运算符。
malloc/free与new/delete的相同点:
1.他们都是用来开辟出一块空间供我们使用;
2.在使用malloc与new的时候必须要与free和delete配对使用,否则会造成内存泄漏。
malloc/free与new/delete的不同点:
1.malloc与free是标准C库函数,而new与delete是C++里面的运算符;
2.new是用来创造对象的,他的执行流程是先申请内存,然后使用类的构造函数来初始化对象,在调用delete时也一样是先调用析构函数,然后再释放内存空间,而malloc
是直接开辟出一块空间,并不会为对象初始化;
3.malloc申请空间后返回的是一个void*类型的指针,我们要在使用时将其强转为我们
要使用的类型,而new返回的是我们所创建对象类型的指针。
4.malloc申请空间时无法对数据初始化,而new会调用构造函数初始化。
例如:
#include<iostream>
using namespace std;
class Point
{
private:
int _x;
int _y;
public:
explicit Point(int x = 0, int y = 0)
:_x(x), _y(y)
{
cout << "Point(int,int)" << endl;
}
~Point()
{
cout << "~Point()" << endl;
}
void Show()const
{
cout << "(" << _x << "," << _y << ")" << endl;
}
};
int main()
{
Point* p = new Point[5];
if (p != NULL)
{
for (int i = 0; i < 5; ++i)
{
p[i].Show();
}
for (int i = 0; i < 5; ++i)
{
delete p;
}
}
return 0;
}
使用new和delete时会调用构造函数与析构函数,并对数据进行初始化!
#include<iostream>
using namespace std;
class Point
{
private:
int _x;
int _y;
public:
explicit Point(int x = 0, int y = 0)
:_x(x), _y(y)
{
cout << "Point(int,int)" << endl;
}
~Point()
{
cout << "~Point()" << endl;
}
void Show()const
{
cout << "(" << _x << "," << _y << ")" << endl;
}
};
int main()
{
Point* p = (Point*)malloc(sizeof(Point) * 5);
if (p != NULL)
{
for (int i = 0; i < 5; ++i)
{
p[i].Show();
}
free(p);
}
return 0;
}
使用malloc与free只是单纯的开辟出一块空间供对象使用,并不会调用构造函数和析构函数,所以不会对数据初始化。