Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand C++ memory processing

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to understand C++ memory processing". In daily operation, I believe many people have doubts about how to understand C++ memory processing. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "how to understand C++ memory processing". Next, please follow the editor to study!

Candlespace + memory distribution

In c and C++, the memory area is roughly divided into these sections: stack area, memory mapping segment, heap area, data segment and code segment.

Stack area: store non-static local variables, function parameters, function return values, etc., which give priority to the use of high address, and gradually down.

Memory mapping segment: an efficient Ithumb O mapping method for loading a shared dynamic memory library. Users can use the system interface to create shared memory and do inter-process communication. As the blogger has not yet updated to the operating system, there is not too much introduction here.

Heap area: used for dynamic memory allocation when the program is running (generally using malloc), which gives priority to the use of low address, gradually upward.

Data segment: stores global data and static variables.

Code snippet: executable code / read-only constant.

If you have a thousand theories, you might as well use an example to show it. Let's move on:

In the above picture, you can clearly see the storage area of various types of data at a glance.

Dynamic memory management in C language

When we are learning c language, we can only apply for a piece of space from the heap area through the malloc () function, and it is troublesome to operate, so we need to calculate the size of the application space and make a forced conversion.

Int* p1 = (int*) malloc (sizeof (int)); free (p1); int* p2 = (int*) calloc (4, sizeof (int)); int* p3 = (int*) realloc (p2, sizeof (int) * 10); free (p3)

We can see clearly that it is a bit tedious to apply for a piece of storage space in C language, so how to apply for a piece of memory in C++ language?

C++ memory management mode

In C++, the memory management mode of c language can still be used, but it is more troublesome to use the method of c in some places, so C++ proposes its own memory management method: dynamic memory management through new and delete operators.

So when will it be troublesome to use c memory management? Such as the following:

Class Stack {public: Stack (int* pcent int n) {val = p; top = capacity = n;} private: int* val; int top; int capacity;}; int main () {Stack* stack = (Stack*) malloc (sizeof (Stack)) / / and now that we want to initialize, we find that it doesn't seem to work (because private members cannot be accessed externally), which will be troublesome, so we propose the operation return 0;} new and delete operation basic types of new and delete.

① opens up the basic syntax of a single element: type* name = new type (content)

① Free Space Syntax: delete name

Where type is the open element type, name is the variable name, and content is the value you want to assign, for example:

Int* a = new int (10); / / opens up an integer space and initializes to 10 position chars = new char ('s'); / / opens up a character space and initializes it to's character space and initializes it to's character space; / / releases an and s

② opens up the basic syntax of array: type* name = new type [n]

② delete array basic syntax: delete [] name

Where type is the element type opened up, name is the array name, and n is the number of spaces, for example:

Int* num = new int [10]; / / Open up 10 spaces of int type char* str = new char [10]; / / Open up 10 spaces of char type delete [] num;delete [] str; / / release num and str

Note: in C language, malloc,realloc,calloc is a function, in C++, new and delete are operators.

Custom types for new and delete operations

The syntax is almost the same as the custom type above, except that the initialization position is a little different. The syntax: type* name = new type (s _ 1 ~ 2 ~ s _ 3.)

Where type is the custom type, and S1, Magi, S2, and S3 are the corresponding parameters of the constructor in the custom type. Example:

Class Test {public: Test (int arecint bline int c) {_ a = a; _ b = b; _ c = c;} private: int _ a; int _ b; int _ c;}; int main () {Test* t = new Test (1Jing 2Jol 3); / / write the corresponding parameters according to the constructor parameter list. Delete t;} Custom types pioneered and initialized based on malloc

Some people might be a little curious and say, I'm just going to open up custom types with malloc, but I still want to initialize and do this? The answer is, yes, it needs to go with new.

Grammar new (type*) type (s 1, 2, 2, 3...)

What do you mean? We still follow the example of the Test class above:

Test* t = (Test*) malloc (sizeof (Test)); new (t) Test (1m 2m 3); / / this initializes the underlying implementation principles of .new and delete.

Before explaining their underlying implementation principle, let's introduce two global functions, operator new and operator delete.

Operator new and operator delete

If you see the above form, it may be mistaken for overloading new and delete, but it is not, it's just that these two functions are called by that name.

When we are learning the C language, do we remember that we need to check whether it is successful or not when opening up the space? Operator new is exactly the same as malloc, except that it reacts to the failure of opening up space by throwing an exception, while in c language, we judge manually and then stop. Here is the code for operator new:

Void* _ _ CRTDECL operator new (size_t size) _ THROW1 (_ STD bad_alloc) {/ / try to allocate size bytes void* p While ((p = malloc (size)) = = 0) / / if it is opened successfully, it will not enter the loop, and it can be clear that if (_ callnewh (size) = = 0) {/ / report no memory / / if the memory application fails An exception of bad_alloc type static const std::bad_alloc nomem will be thrown here _ RAISE (nomem);} return (p);}

In the same way, operator delete is just free, and here's the code:

Void operator delete (void* pUserData) {_ CrtMemBlockHeader* pHead; RTCCALLBACK (_ RTC_Free_hook, (pUserData, 0)); if (pUserData = = NULL) return; _ mlock (_ HEAP_LOCK); / * block other threads * / _ _ TRY / * get a pointer to memory block header * / pHead = pHdr (pUserData) / * verify block type * / _ ASSERTE (_ BLOCK_TYPE_IS_VALID (pHead- > nBlockUse)); _ free_dbg (pUserData, pHead- > nBlockUse); _ _ FINALLY _ munlock (_ HEAP_LOCK); / * release other threads * / _ _ END_TRY_FINALLY return;}

Conclusion: operator new is actually the encapsulation of malloc, and operator delete is the encapsulation of heap free.

The underlying implementation of new

The implementation of new is actually a further encapsulation of malloc, because the operation of new can be divided into two things:

Call operator new to open up space.

If the open space is a custom type, new calls its constructor.

Therefore, the interior of new is actually encapsulated by constructors and operator new.

The underlying implementation of delete

By the same token, delete is just a further encapsulation of free, because the operation of delete can be divided into two things:

If the space opened by new is a custom type, its destructor is called first to release its internal resources.

Then call operator delete to release the space opened up by new.

Note that some people here may not understand what it means to release the inner part of the custom type first and then destroy the outer space. The blogger draws a picture here, but let's take a look at the following class:

Class Stack {public: Stack (): num (new int [10]), top (0), capacity (10) {} ~ Stack () {delete [] num; top = capacity = 0;} private: int* num; int top; int capacity;} Int main () {Stack stack; delete stack; return 0;}

If we define this object, its spatial distribution is as follows:

If delete does not call the destructor first, after releasing the stack object, the num in the heap area will continue to exist, resulting in a memory leak.

The underlying implementation of new []

1. Call the operator new [] function, and actually call the operator new function in operator new [] to complete the application of N object spaces.

two。 Execute the N-time constructor on the applied space

Principle of delete []

1. Execute the N-th destructor on the released object space to clean up the resources in N objects.

two。 Call operator delete [] to free up space, and actually call operator delete in operator delete [] to free up space

At this point, the study on "how to understand C++ memory processing" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report