malloc和new的区别
- 他们都是动态管理内存的入口。
- malloc/free是C/C++标准库函数,new/delete是C++操作符。
- malloc只是动态开空间释放空间,而new动态开空间并调用构造函数(初始化)和析构函数(清理)
- malloc/free需要手动计算类型大小且返回值为void*,new/delete可自己计算类型,返回对应类型的指针。
new底层原理:
- 开空间。调用operator new--->malloc
- 调用构造函数
- 调用析构函数
- 释放空间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");
}
结果: