How to use new and delete in C++
This article is about how to use new and delete in C++. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
new and delete are called operators
Let's turn to disassembly and see
These two operators are essentially overloaded calls to the corresponding operators
What is the difference between malloc and new?
1.malloc opens memory by byte;new opens memory by specifying type new int[10]
So malloc opens up memory and returns void*
new is equivalent to the overloaded function operator new -> returns automatically to the specified class pointer int*
2.malloc is only responsible for opening up space, new not only has the function of malloc, but can initialize data.
new int(20);//initialize 20 new int[20]();//open array does not support initialization values, but supports writing empty parentheses, indicating that each element is initialized to 0, equivalent to calling int () to 0 for each element
3.malloc fails to open memory and returns nullptr pointer;new throws an exception of type bad_alloc
(That is, the new operator fails to open up memory. To expand its code into try catch, it cannot be compared with a null pointer by returning a value.)
try//The code for possible errors is placed in try { int *p = new int; delete []p; int *q = new int[10]; delete q; } catch (const bad_alloc &err)//catch exceptions of the corresponding type { cerr Call to operator delete overloaded function
Define the overloaded functions of new and delete in the global place, so that only the places involving new and delete in our entire project will call the overloaded functions of new and delete that we rewrite globally.
//first call operator new to open up memory space, and then call the object constructor (initialization) void* operator new(size_t size){ void *p = malloc(size); if (p == nullptr) throw bad_alloc(); cout