C++ basic syntax - new, delete to open/destroy dynamic memory space

Preface: In C language, there are malloc, realloc, calloc to open up dynamic memory space, and free to destroy dynamic memory space. In C++, use new to open up dynamic memory space, and delete to destroy dynamic memory space. Not only does it simplify the operation, but more importantly,Solve the initialization problem of custom type

1. Simplify operations

Usage: new 类型 delete 指针
Create an array: new 类型[数据个数] delete[] 指针
the compiler will automatically calculate the size of the type, and there is no need to cast the type. It greatly simplifies the operation, but remember the following three sentences: Be sure to match and use! Match to use! Match to use!

	//int* a = (int*)malloc(sizeof(int));
	//free(a);
	int* a = new int;
	delete a;
	int* b = new int[10];
	delete[] a;

2. Solve the problem of custom type initialization (key point)

The biggest difference between new/delete and malloc/free is that new/delete will open space for custom typesCall their constructors/destructors.
new will call the constructor, and delete will call the destructor.

Take the stack class as an example:

typedef int DataType;
class Stack {
    
    
public:
	Stack(int capacity = 4)//构造函数 
	{
    
    
		_arr = new DataType[capacity];
		_capacity = capacity;
		_size = 0;
	}
	void StackPush(DataType Data)
	{
    
    
		_arr[_size] = Data;
		_size++;
	}
	~Stack() //析构函数
	{
    
    
		delete[] _arr;
		_capacity = _size = 0;
	}
private:
	DataType* _arr;
	int _capacity;
	int _size;
};
int main()
{
    
    
	Stack* ptr = (Stack*)malloc(sizeof(Stack)); //malloc开辟一个自定义的栈对象
	ptr->StackPush(1); //压栈
	free(ptr);
	return 0;
}

The console display is as follows: We know that if it is not 0, it means that the program is wrong, so why is the above code wrong? This is what we emphasizemalloc is just to open up space, and will not call the constructor of the custom type Stack, there is no initialization, and if there is no initialization and pushing it into the stack, an error will definitely occur.
Insert image description here

Changing to new and delete will not report an error:

int main()
{
    
    
	Stack* ptr = new Stack;
	ptr->StackPush(1);
	delete ptr;
	//free(ptr)  不行,free不会去调用析构函数,资源得不到清理。
	return 0;
}

3. New does not check for failure and throws an exception.

When we use malloc to open up space, we usually write an if conditional statement to prevent space opening failure, but new no longer checks for failure, and will directly throw an exception when an error occurs. That is to say, when using new, there is no need to write an if condition to prevent space opening failure.

void Func()
{
    
    
	//malloc
	int* a = (int*)malloc(sizeof(int)*10);
	if (a == nullptr) //if判断
	{
    
    
		return;
	}
	free(a);
	//new
	int* b = new int[10];
	delete[] b;
}

1. Throw an exception

Using malloc to open up the same size space will not prompt an error, but new will.
Insert image description here

2. Catch exceptions (try catch)

Use try and catch to catch exceptions and find the cause of the exception.

int main()
{
    
    
	try
	{
    
    
		char* p2 = new char[0x7fffffff];
	}
	catch (const exception& error)
	{
    
    
		cout << error.what() << endl;
	}
	

The console displays as follows:
Insert image description here

After an exception occurs, the execution flow jumps, and the code after the exception is not executed:

int main()
{
    
    
	try
	{
    
    
		cout << "正常" << endl;
		char* p2 = new char[0x7fffffff];
		cout << "异常" << endl;
	}
	catch (const exception& error)
	{
    
    
		cout << error.what() << endl;
	}
	return 0;
}

The console output is as follows: It can be seen that the code that outputs "exception" has not been executed. This is similar to the goto statement. After an exception occurs, it jumps directly to the catch statement. This design avoids running subsequent statements when an error occurs, and prevents mistakes from being compounded.
Insert image description here

4. operator new/operator delete function

new and delete are operators for users to apply for and release dynamic memory. Operator new and operator delete are global functions provided by the system. new calls the operator new global function in the dungeon to apply for space, and delete uses the operator delete global function to release it at the bottom. space.

operator new is an encapsulation of the malloc function, that is to say, the space generated by new is actually generated by malloc. The difference is that the malloc function will return NULL if an error occurs, but C++ needs to return an exception if an error occurs, so the malloc function is encapsulated, but an error returns an exception.
The principle of operator delete is similar to operator.

As follows: operator new/operator delete is used in the same way as malloc/free.

	int* a = (int*)malloc(sizeof(int) * 10);
	free(a);
	int* b = (int*)operator new(sizeof(int) * 10);
	operator delete(b);

1. Built-in types

From the above, if you are applying for a built-in type of space, new and malloc, delete and free are basically similar. The difference is: new/delete applies for and releases space for a single element, while new[] and delete[] apply for and releases continuous space, and new will throw an exception when it fails to apply for space, and malloc will return NULL.

The following three methods can all release space. In fact, they all use free to release space. But the first and second options are not recommended. Be sure to usematch use. to avoid special situations.

	int* a = new int[10];
	//都可以释放申请的空间
	//free(a);
	//delete a;
	delete[] a;

2. Custom type

  1. The principle of new
    1. Call the operator new function to apply for space
    2. Execute the constructor on the applied space to complete object initialization.
  2. The principle of delete
    1. Execute the destructor on the space to complete the cleanup of resources in the object.
    2. Call the operator delete function to release the object's space.
  3. Principle of new T[n]
    1. Call the operator new[] function, and actually call the operator new function in operator new[] to complete the application for n object spaces.
    2.Execute the constructor n times on the requested space
  4. Principle of delete[]
    1. Execute n destructors on the released object space to complete the cleanup of resources in n objects.
    2. Call operator delete[] to release space. Actually, operator delete is called in operator delete[] to release space.

BB at the end of the article: For friends who have any questions, feel free to leave a message in the comment area. If there are any questions, friends are welcome to point out in the comment area. The blogger will confirm the modification as soon as possible after seeing it. Finally, it is not easy to make. If it is helpful to friends, I hope to give the blogger some likes and attention.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_73390155/article/details/132378490