Article Directory
- Usage of new and delete
- Dynamic creation and release of class objects
Usage of new and delete
1) In the process of software development, it is often necessary to dynamically allocate and undo memory space, such as inserting and deleting nodes in dynamic linked lists. In C language, library functions malloc and free are used to allocate and undo memory space. C++ provides simpler and more powerful operators new and delete to replace malloc and free functions.
Note: new and delete are operators, not functions, so they are efficient in execution.
2) Although C++ still retains malloc and free functions for compatibility with C language, it is recommended that users do not use malloc and free functions, but use new and delete operators. Example of new operator:
new int; //Open a storage space for storing integers and return an address (i.e. pointer) to the storage space
new int(100); //Open a space for storing integers, and specify that the initial value of the integer is 100, and return an address pointing to the storage space.
new char[10]; //Open a space to store character array (including 10 elements), and return the address of the first element
new int[5][4]; //Open a space to store two-dimensional integer array (size 5*4), return the address of the first element
float *p=new float (3.14159); //Open a space for storing single-precision numbers, and specify that the initial value of the real number is //3.14159, assign the address of the returned space to the pointer variable p
The initial value cannot be specified when allocating array space with new. If the space cannot be allocated normally due to insufficient memory or other reasons, new will return a null pointer NULL, and the user can judge whether the allocation of space is successful based on the value of the pointer.
Dynamic creation and release of class objects
Objects defined using class names are static, and during the program operation, the space occupied by the object cannot be released at any time. But sometimes people want to create an object when it needs to be used, and undo it when it does not need to be used, freeing the memory space it occupies for other data. This can improve memory space utilization.
In C++, you can use the new operator to create objects dynamically and use the delete operator to undo the objects.
for example:
Box *pt; //Define a pointer variable pt to a Box class object
pt=new Box; //Storing the starting address of the newly created object in pt is stored in pt
This newly created object can be accessed through pt in the program. like
cout<height; //Output the height member of the object
cout<volume( ); //Calculate the volume function of the object, calculate and output the volume
C++ also allows the newly created objects to be initialized when new is executed. like
Box *pt=new Box(12,15,18);
This way of writing is to combine the above two statements (defining pointer variables and creating new objects with new) into one statement and specify the initial value. This is more refined.
The height, width and length in the new object get initial values 12, 15, and 18, respectively. The call object can be either through the object name or through the pointer.
When performing new operations, if the amount of memory is insufficient and the required memory space cannot be opened, most C++ compilation systems currently make new return a pointer value of 0. As long as you check whether the return value is 0, you can determine whether the allocated memory is successful.
The ANSI C++ standard proposes that when a failure occurs when a new execution occurs, an "exception" is "thrown" and the user can perform relevant processing based on the exception. However, the C++ standard still allows returning a 0 pointer value in the event of a new failure. Currently, different compilation systems deal with new failures differently.
When objects created by new are no longer needed, they can be released with the delete operator. like
delete pt; //Release the memory space pointed to by pt
This undoes the object pointed to by pt. The program can no longer use the object.
If you use a pointer variable pt to point to different dynamic objects one after another, you should pay attention to the current pointer variable to avoid deleting the wrong object. When executing the delete operator, the destructor is automatically called before freeing up the memory space to complete the aftermath cleaning work.
Sample program:
#include <iostream>
#include <>
using namespace std;
// C:malloc and free C++: Space management on the heaps
// malloc and free are library functions. Functions provided by the C language standard library are not part of C language syntax.
// new delete operators of C++ Part of C++ syntax new and delete are more efficient than malloc and free
// Basic data type space allocation
int func5_1()
{
// Allocate an integer space
int *p1 = (int *)malloc(sizeof(int)/sizeof(char));
*p1 = 10;
cout << *p1 << endl;
// Release
free(p1);
p1 = NULL;
// C++ new delete
// new : new data type
int *p2 = new int; // Allocate an integer space
*p2 = 12;
cout << *p2 << endl;
delete p2; // Free space
// It can be initialized directly when new
// new data type (initial value)
int *p3 = new int(5);
cout << *p3 << endl;
delete p3;
return 0;
}
// Dynamically allocate arrays (a continuous space)
void func5_2()
{
// C: Assign array int a[100];
int *p = (int *)malloc(sizeof(int)/sizeof(char)*100);
// Release
free(p);
// C++:
// new : new data type [number]
// new can not be initialized when allocating arrays
int *p1 = new int[100];
// Free array: delete []
// Not adding [] will cause memory leakage
delete [] p1;
}
class Test5_1
{
public:
Test5_1()
{
cout << "Constructor is called" << endl;
}
Test5_1(int a)
{
m_a = a;
cout << "Constructor Test5_1(int a) is called" << endl;
}
~Test5_1()
{
cout << "The destructor is called" << endl;
}
private:
int m_a;
};
// Dynamically allocate objects
void func5_3()
{
// C language only allocates the space of an object on the heap
Test5_1 *p1 = (Test5_1*)malloc(sizeof(Test5_1)/sizeof(char));
free (p1);
// C++
// When new object, the object's constructor will be called to initialize the object
Test5_1 *p2 = new Test5_1;
// When delete, the object's destructor will be called to retrieve the object's resources
delete p2;
Test5_1 *p3 = new Test5_1(10); // Parameter-like structure
delete p3;
}
int main)
{
func5_1();
func5_2();
func5_3();
return 0;
}
func5_1() execution result:
10
12
5
func5_3() execution result:
The constructor is called
The destructor is called
The constructor Test(int a) is called
The destructor is called