malloc/free与new/delete的异同处

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只是单纯的开辟出一块空间供对象使用,并不会调用构造函数和析构函数,所以不会对数据初始化。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值