The difference between new, delete and malloc, free

First of all,
new and delete are C++ keywords and need to be supported by the compiler to support
malloc. Free is a library function of C and requires header files.

At the same time,
new will automatically allocate memory according to the data type when opening up the memory , without manual specification,
while malloc needs to manually specify the size of the required memory

Etc. After successfully opened memory
new return is consistent with the type of object pointers
and the malloc returns * void, people need a cast

Of course, there are failures,
so it needs to be tested.
If it fails,
new will throw a bad_alloc exception,
malloc will return a null pointer.
According to the difference of the return, you can determine whether the memory is successfully opened.

Implementation steps of new
1. First use operator new to open up a memory space

2. Call the constructor of the class

3. Return the corresponding pointer

For different classes, operator new often needs to be overloaded multiple times to achieve different

Finally, there is
an understanding of stack and heap and object creation A a and A *p = new a:

栈是连续内存,由系统来控制,其内的数据执行完就自动删除

而A a就是静态建立对象,由系统直接在栈中开辟内存------移动栈指针,然后直接调用构造函数并在执行完后自动删除


堆是不连续内存,不受系统控制,其内的数据不会自动删除,容量较大
A *p =new a 则是动态建立对象,在堆中进行,先调用合适的operator new()函数来开辟内存空间,然后再调用函数的构造函数

Both malloc and free are performed on the heap,
and new is the memory opened up on the heap by malloc, so you also need to delete
it yourself. Here,
the bottom layer of delete is used , and the destructor of the class is called first, and then used free to free up memory space

Then the difference between the two can be understood like this

malloc,free只是单纯的对内存的开辟和释放,它不负责任何东西

而new和delete,会根据对象的不同,来进行构造和析构,并返回对应的指针类型

也就是说new是建立在c++面向对象的特性上建立的,更加完善的为对象服务的开辟以及删除内存的关键字

Guess you like

Origin blog.csdn.net/qq_43624038/article/details/114294174