——————————————————————————————————————————————————————————
Life is like a flash of time, love and hate can become mist and clouds, fame and fortune will eventually be like dirt, only time cannot be let down.
——————————————————————————————————————————————————————————
1. The basics of new operations
In software development projects, we often need to dynamically allocate and free memory space. In C language, we use malloc and free.
Simpler operators new and delete are provided in C++.
Example of new operator
new int ; // Create a storage space for storing integers and return an address pointing to the storage space
new int(100);
new int [3][6]; //Open a storage space for storing two-dimensional arrays and return the address of the first element
The initial value cannot be specified when allocating array space with new. If the allocation fails due to insufficient memory or other reasons, a NULL pointer is returned.
delete operator format:delete[ ] pointer variable
float *p = new float(3.14);
delete p;
new char[10];
delete[] pt; //Add [] in front of the pointer to indicate the operation of array space
2. New operator dynamically creates objects
//Define class Box
Box *pt; //Define the value of a pointer to a new object
pt = new Box; //Storing the starting address of the newly created object in pt
//You can access this address in the program
cout <<p->height; //The height member of the output object
cout<<p->volume();//Output object member function
Box* pt = new Box(12,12,12);
When new fails to open up space, the return value is 0.
When you don't need to use new to create objects, you can use delete to delete.
detele pt; //Release the memory space pointed to by pt
When pointing to the delete operator, the destructor is automatically called before the memory is freed.