1. What are new and delete
We know that in C language, the method to dynamically open memory is to use: malloc/calloc/realloc. Free the memory that is dynamically opened is free. In C++, another new gameplay was introduced:new and delete. In C++, new is used to dynamically open up memory, delete is used to free up the memory we dynamically open.
In C language, the function we often use for dynamic development of built-in types is the malloc function. In C++, we can also use the new operator to apply space dynamically. Note: We found the first difference between malloc and new here.malloc is a function, new is an operator. Of course, the free that appears in pairs is a function and delete is an operator.Let's first look at the comparison of its usage methods, the code is as follows:
void Test() { // Dynamically apply for an int-type space int* p1 = malloc(sizeof(int)); int* p2 = new int; // Dynamically apply for an int type space and initialize it to 10 int* p3 = malloc(sizeof(int)); *p3 = 10; int* p4 = new int(10); // Dynamically apply for 10 int-type spaces int* p5 = malloc(sizeof(int) * 3); int* p6 = new int[3]; //release free(p1); delete p2; free(p3); delete p4; free(p5); delete[] p6; }
Through the above comparison, we can clearly feel that new and delete are more convenient to use. Because when we use new to dynamically open space, we do not need to calculate the size of the opened space type. Because the type is followed by, new will automatically calculate the size of the type.
We also found that new can also be initialized when dynamically opening up memory. After malloc is opened, it can be initialized by dereference. When new is dynamically opening an array, it can also be initialized, but this is only the syntax that C++11 has only supported, and the usage is as follows:
int* p6 = new int[10]{1,2,3}; delete[] p6; //The value not given later,It will be automatically initialized to0。
2. The difference between new and malloc
The difference between new and malloc:
It is a C library function, and new is an operator.
The return value must be cast, and the return value of new is not required.
A specific number of bytes must be passed in, and a new number of variables or variables themselves must be passed in.
If the application fails, it will return empty, and new will throw an exception.
5. When creating an object of a class using new, malloc will be called first to allocate space, and then the constructor will be called to assign values to member variables.
6. New and delete will automatically call the constructor and destructor when applying for space for custom classes.
This is the article about the difference analysis of the new and delete operators in C++ and the new and malloc. For more related contents of the c++ new and delete operators, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!