new
and delete
are operators , malloc
and free
are library functions .
Execution new
actually performs two operations: 1. Allocate uninitialized memory space, that is, call malloc
library functions. 2. Use the constructor of the object to initialize the space and return the first address of the space.
std::bad_alloc
If there is a problem with allocating space in the first step, an exception will be thrown directly , or it will be handled by a set exception handling function. If an exception occurs in the second step of constructing the object, call to delete
release the memory.
There are actually two processes in execution delete
: 1. Use the destructor to destruct the object. 2. Reclaim the memory space, that is, call free
the library function.
new
The difference between and malloc
: new
What you get is initialized space, and malloc
what you get is uninitialized space. So new
it is new
a type, but malloc
it is malloc
a byte-length space. new
Use std::bad_alloc
the exception to judge whether the space allocation is successful, and malloc
use the return value and nullptr
comparison to judge whether the space allocation is successful. malloc
The creation space itself is typeless.
delete
The difference between and free
: delete
Not only will the space be released, but the object will also be destructed. delete
One type, free
one byte length space.
malloc/free
Why is there a need when there is already new/delete
? Because for non-internal data types (custom objects, etc.), light use malloc/free
cannot meet the requirements of dynamic objects. The object needs to automatically execute the constructor when it is created, and the object automatically executes the destructor before it dies. Because malloc/free
it is a library function rather than an operator, it is not within the control authority of the compiler, and the task of executing the constructor and destructor cannot be imposed on it malloc/free
, so there is new/delete
an operator.
new initializes variables and constant pointers
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 4种new初始化
int *p1 = new int(20); // 最正常的
int *p2 = new (nothrow) int(20); // 不会抛出异常的
const int *p3 = new const int(20); // 常量指针类型
int a = 0;
int *p4 = new (&a) int(50); // 定位new,将原来变量a的地址中的值改为当前初始化的值,p4的地址和a的地址一致
// 0x632410 0x632450 0x632490 0x61fdfc 50 0x61fdfc
cout << p1 << " " << p2 << " " << p3 << " " << p4 << " " << a << " " << &a << endl;
return 0;
}
The difference between new/malloc and delete/free in general use
#include <iostream>
#include <string>
using namespace std;
int main()
{
int *p1 = (int*)malloc(sizeof(int)); // malloc创建空间,并强制转化给它一个类型
if(p1==nullptr) // 判断空间是否分配成功
{
return -1;
}
*p1 = 20;
free(p1); //释放指针
int *p2 = new int(20);
delete p2;
int *p3 = (int *)malloc(sizeof(int) * 10); // 创建长度为10的数组,返回的是数组空间的首地址
if(p3==nullptr)
{
return -1;
}
free(p3);
int *p4 = new int[10](); // 创建长度为10的数组,返回的是数组空间的首地址
delete[] p4;
return 0;
}