Identify malloc and New in C + + using an example of authoritative persuasion
Problem:
Many people know that malloc and new are used to apply for space, and that space comes from the heap. But in C + + there is little use of malloc to apply for space, why?
The following small series will be a very convincing example to illustrate, I believe that we can understand it at a glance.
The layout of C + + programs can be divided into 4 zones, which are "pattern",
1. Global data area//global variable, static variable belongs to global data area
2. Code area // all classes and non-member functions are stored in the code area
3. The space of the local variables allocated for the run of the member function in the stack area
4, the heap area// the rest of the space belong to the heap area
Where global variables, static variables are the global data area, all the code of the class and non-member functions are stored in the code area, and the space for the local variables allocated for the member function runs is in the stack area, and the remaining space belongs to the heap.
Let's write a simple example: malloc.cpp
#include <iostream>using namespace std; #include <stdlib.h>class test{public : Test () { cout << "The Class has constructed" <<endl; } ~test () { cout<< "the Class has disconstructed" <<endl; } ; int main () { Test *p = (test*) malloc (sizeof (Test)); Free (p); Delete p; return 0;}
Compile run: The Class has disconstructed
The result is that the constructor is not called, and as you can see from this example, malloc is only responsible for allocating space to the object pointer instead of invoking the constructor to initialize it. The object construction of a class in C + + requires the allocation of space, the invocation of a constructor, the initialization of a member, or an initialization of an object. Using the above example, I hope you will try not to use malloc in C + +, but to use new.
<span style= "FONT-SIZE:14PX;" > #include <iostream>using namespace std; #include <stdlib.h>class test{public : Test () { cout<< "The Class has constructed" <<endl; } ~test () { cout<< "the Class has disconstructed" <<endl; } ; int main () { //test *p = (test*) malloc (sizeof (Test)); Test *p = new test; cout<< "Test" <<endl; Free (p); Delete p; return 0;} </span>
The results of the operation are as follows:
the Class has constructed
the Class has disconstructed
If you want to learn more about the similarities and differences of C + + New/delete,malloc/free, you can read more about "Deep C + + new/delete,malloc/free parsing".
Identify malloc and New in C + + using an example of authoritative persuasion