【C++】new/delete底层原理和new[]/delete[]

malloc和new的区别

  1. 他们都是动态管理内存的入口。
  2. malloc/free是C/C++标准库函数,new/delete是C++操作符。
  3. malloc只是动态开空间释放空间,而new动态开空间并调用构造函数(初始化)和析构函数(清理)
  4. malloc/free需要手动计算类型大小且返回值为void*,new/delete可自己计算类型,返回对应类型的指针。

new底层原理:

  1. 开空间。调用operator new--->malloc
  2. 调用构造函数
  3. 调用析构函数
  4. 释放空间operator delete----->free

定位new表达式

定位new表达式是在已分配的原始内存空间中调用构造函数初始化一个对象。

new(place_address) type

new(place_address) type(initializer-list)

place_address必须是一个指针,initialzer_list是类型的初始化列表

class Array{
public:
	Array(size_t size = 10)
		: _size(size)
		, _a(0)
	{
		cout << "Array(size_t size)" << endl;
		if (_size > 0)
		{
			_a = new int[size];
		}
	}
	~Array()
	{
		cout << "~Array()" << endl;
		if (_a)
		{
			delete[] _a;
			_a = 0;
			_size = 0;
		}
	}
private:
	int* _a;
	size_t _size;
};
void Test()
{
	// 1.malloc/free + 定位操作符new()/显示调用析构函数,模拟 new和delete 的行为
	Array* p1 = (Array*)malloc(sizeof (Array));
	new(p1)Array(100);
	p1->~Array();
	free(p1);
	// 1.malloc/free + 多次调用定位操作符new()/显示调用析构函数,模拟 new[]和delete[] 的行为
	Array* p2 = (Array*)malloc(sizeof (Array)* 10);
	for (int i = 0; i < 10; ++i)
	{
		new(p2 + i) Array;
	}
	for (int i = 0; i < 10; ++i)
	{
		p2[i].~Array();
	}
	free(p2);	
}
int main()
{
	Test();
	system("pasue");
}

 

结果:

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值