Plants vs. Dynamic Memory - C++

foreword

Summarize and review the previous knowledge.

Note: After learning C++, you don't have to use classes when doing oj questions.
You can choose the simplest one from multiple options. How simple how to write.

An anonymous object can be defined with a class name.
The declaration cycle of the anonymous object is only in that line.

weight();//匿名对象,匿名周期就是当前行。

If construction + copy construction run together, the compiler will optimize the steps.

f(weight());//先构造匿名对象weight(),然后再传参拷贝构造。

Conclusion: In an expression, the construction of successive steps + copy construction
or copy construction + copy construction. Bold compilers will optimize and combine the two into one.

dynamic memory allocation

At the top is the stack. Then there is the heap, the static area (the system is called the data segment), and the constant area (code segment). The code here is not the code we wrote, but those instructions.

The stack and the heap open up space only after the program runs.

Why are these areas differentiated?
Because different data need to exist in different locations.

int glob = 1;
static int staticglob = 1;
void test()
{
    
    
	static int staticvar = 1;
	int loacalvar = 1;
	int num1[10] = {
    
    1,2,3,4};
	char char2[] = "abcd";
	char* pchar3 = "abcd";
	int* ptr1 = (int*)malloc(sizeof(int)*4);
	int* ptr2 =(int*)calloc(4,sizeof(int));
	int* ptr3 = (int*)realloc(ptr2,sizeof(int)*4);
}

globalvar is a global variable, and global variables are in the static area from the perspective of language. From the system look in the data segment.

staticgob is a static variable, also in the static area.

staticvar is a static variable, in the static area

Summary: The declaration cycles of global variables and static variables are global. So they are all in the static area.

localvar is a local variable, and local variables are created on the stack.

num1 represents this array, and the array is on the stack.

char2 is on the stack. char2 is an array, this array is on the stack. He is initialized with a copy of the constant string abcd ** in the past . Note the copy**.

*char2 is also on the stack. Because it represents the content pointed to by this array, and the content is also on the stack.

pchar3 is also on the stack

*pchar3 dereferencing gets the string abcd in the constant area, so it is in the constant area.

ptr1 is on the stack.

*ptr1 is on the heap. Because he was developed by malloc.

The const modified is called a constant variable, and the constant variable is on the stack.

How to understand the increase of C++ syntax

Such as function overloading, references, new/delete, stream insertion and stream extraction operators. classes and objects.

They are all to make up for the shortcomings of the C language. Maybe the inventor of C++ wrote in C at the time

new

What is the difference between malloc and calloc?
malloc is open space.
calloc is open space + initialization.

realloc is for capacity expansion, if there is space, it can be expanded in situ, if there is no space, it can be expanded in different places.

The C language already has a method for opening spaces. Why did C++ create a new?

New and delete are used together.
new is to solve the unusable places in C language.

new usage

new is to open the space first, and then call the constructor to initialize. ,
for the built-in types, there is no difference between using malloc and new except for the usage. The difference between them is the custom type.

//new 一个对象
int* p1 = new int;
//new 10个对象
int* p2 = new int[10];
//new一个对象初始化为10
int* p3 = new int(10);
//C++11的数组初始化
int* p4= new int[10]{
    
    10,1,2,3};

//初始化时一定要匹配释放。
delete p1;
delete[] p2;
delete p3;
delete[] p4;

For the custom type linked list creation node.

struct ListNode
{
    
    
	ListNode* next;
	int val;
	//构造函数
	ListNode(int val = 0)
		:_next(nullptr)
		,_val(val)
	{
    
    }
};


The following is the usage of C language, which is particularly troublesome.
insert image description here
But for C++. C++ can use new directly, because new will automatically call the constructor. If the constructor is written, it will be automatically initialized.

ListNode* n = new ListNode;

About the use of struct and class

The struct is shared by default, and the settings that must be accessed are generally public, such as the node ListNode of the list.

Members of a class are private by default.

The difference between free and delete.

Free directly releases the current pointer pointed to. Regardless of the pointer of the pointer, it is easy to cause a memory leak.

And delete will carry out the following two steps.

1. Call the destructor first, and then release resources such as pointers in the destructor to release the space. Hand it back to the OS.
2. Release the space pointed by the current pointer.

memorize this sentence

The constructor will be called when the object is created. If it is not written, there is a default constructor. No processing is done for built-in types, and its default constructor is called for custom types.

throw exception

1. For the C language, we need to check the failure to open up space, plus assert, malloc will return a null pointer if it fails.

2. For C++ new, an exception will be thrown if it fails to open up space .

How to catch the exception?
The principle of exceptions is implemented based on inheritance and polymorphism.

For example, the following code throws an exception,
try and catch will be executed one of the two. When an exception is thrown, the catch is executed.

try
{
    
    	
	void* p2 = new char[124*1024*1024];
}
catch(const exception& e)
{
    
    
	cout << e.what() << endl;
}

Do we need to throw exceptions when we usually use new?
The answer is no. Exceptions are generally checked outside the function.

operator new and operator delete

Key points: The underlying principle of new is to call operator new and constructors.

Be careful. Although this has the word operator, it is not overloading new .

In fact, this operator new encapsulates malloc, and an exception is thrown when malloc fails.
operator encapsulates free.

Is there any difference between these two essences and malloc? Actually there is no difference. The function is the same, and no exception is thrown after failure.

Open space example.

Stack* st = (Stack*)operator new(sizeof(Stack));
operator delete(st);

What is the use of operator new?
It is designed for new.
new calls operator new and the constructor. ! !
The role of operator new is to call malloc, if malloc then throw an exception. If successful, proceed to the constructor.

The role of the constructor is to initialize.

memory pool

If we frequently apply for and release space from the heap, we can use a memory pool at this time, because the memory pool is faster and can improve efficiency.

Because operator new needs to be called in the middle of the heap, and operator new needs to call mallo again, which is very costly.

The memory in the memory pool can be used directly, and the efficiency is very fast.

C++'s overloaded new can solve the problem of inefficiency caused by calling new directly.

It is to overload new. to call the memory pool.
Overload delete and call the memory pool directly.

The principle of new and delete

new

  1. Call the operator new function to apply for space

  2. Execute the constructor on the requested space to complete the construction of the object

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 space of the object#

The 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 of N object spaces
  2. Execute the constructor N times on the requested space

The principle of delete[]

  1. Execute N times of destructors on the released object space to complete the cleanup of resources in N objects
  2. Call operator delete[] to release space, actually call operator delete in operator delete[] to release space

positioning new

For a space, call the constructor to initialize the
example

Stack* obj  = (Stack*)operator new(sizeof(Stack));
new(obj)Stack(4);

//相当于
Stack* obj = new Stack(4);

What is the difference between malloc and new?

How to consider this issue?
1. The difference in usage
2. The difference in the bottom layer
malloc and free are functions, and new and delete are operators.

The underlying difference is that new calls the constructor.
free will call the destructor.

memory leak

What is a memory leak?

A memory leak means that the pointer is lost. It returns the memory to the operating system.

What is the real danger of a memory leak?

We don't have to be afraid of ordinary memory leaks, even if we don't release them. After the normal program ends, the memory is returned to the operating system.

What are you afraid of?
The fear is that our computer memory is very small, or programs that run for a long time, need to be deleted when using them at this time.

Guess you like

Origin blog.csdn.net/qq2466200050/article/details/128539452