C ++ language guide (15th)-dynamic memory

Source: Internet
Author: User

**********************************
Link: http://www.cplusplus.com/doc/tutorial/

**********************************

Dynamic Memory
In all our programs, all the valid memory I own is the variable we declare. In the source program, all their sizes are determined before the program runs. However, what if we need a block to determine the size of a variable total memory at runtime? For example, when we need user input to determine the total amount of memory space required. The answer is Dynamic Memory ( Dynamic Memory )For this reason, C ++ integrates Operators NewAnd Delete.


Your ad here

Operator New And New []To request dynamic memory, we use the new operator. New follows a data type specifier and -- if a request contains a sequence of more than one element -- the number of these elements is enclosed in square brackets. It returns a pointer to the beginning of the allocated new memory block. The format is as follows:

Pointer = New Type
Pointer = new type [elements]

The first expression is used to assign a unique TypeMemory of type elements. The second is used to allocate TypeMemory of A type element, where ElementsIs an integer value indicating the number of these elements. For example:
Int * Bobby;Bobby = new int [5];
In this case, the system has five IntType elements dynamically allocate space and return a pointer pointing to the first element of the sequence, which is assigned Bobby. So now, BobbyPoint to a valid memory block, which has five IntType element.
Quilt BobbyThe first element to be pointed to can be indicated by an expression. BOBBY [0]Or expression * Bobby. The two of them are equivalent, as explained in the section about pointers. The second element can be used. BOBBY [1]Or * (Bobby + 1)And so on ...... You may be surprised at the difference between declaring a common array and allocating dynamic memory to pointers, as we did just now. The main difference is that the size of an array is a constant value, which limits its size to the value we decided during program design before it runs; in turn, dynamic memory allocation allows us to allocate memory during program execution (runtime), using any variable or constant as its size. The dynamic memory requested by our program is allocated by the system from the memory heap. However, the computer memory is a limited resource that can be used up. Therefore, some mechanisms are very important to detect the success of our memory allocation requests. C ++ provides two standard methods to check whether the allocation is successful: one is to handle exceptions. This method throws Bad_allocType exception. Exceptions are a powerful C ++ feature that will be described later in this Guide. But now, you should understand that if this exception is thrown and not handled by any specific handler, the program will be terminated. This exception method is NewThe default method used, and is used in a declaration like this:
Bobby = new int [5];// If it fails an exception is thrown
Another method is called Nothrow (Do not throw)", When it is used and a memory allocation fails, it will not throw Bad_allocException or termination of the program, NewThe returned pointer is NullPointer, and the program continues to run. This method can be called by using a special NothrowObject NewParameters to specify:
Bobby = new (nothrow) int [5];
In this case, if the memory allocation fails, you can check whether BobbyWith NullPointer value to find:
Int * Bobby; Bobby = new (nothrow) int [5]; If (Bobby = 0 ){

// Error assigning memory. Take measures.

};
This NothrowThe method requires more work than the exception method because the returned value must be checked after each memory allocation, but I will use it in our example because of its simplicity. In short, this method will become annoying for larger projects, while exception methods are usually better. The exception method will be described in detail later in this Guide. Operator Delete And Delete []Because the need for dynamic memory is usually limited to a specific time in a program, it should be released once it is no longer needed, to make that memory change another request to other dynamic memory valid. This is an operator DeleteIn the form:
Delete pointer;Delete [] pointer;
The first expression is used to delete the memory allocated for a single element, and the second is used to release the memory allocated for a group of elements. Passed DeleteMust be NewThe pointer to the allocated memory block, or NullPointer (in NullPointer, Delete).
// Rememb-o-matic# Include <iostream>Using namespace STD; Int main (){Int I, N;Int * P;Cout <"How many numbers wocould you like to type? ";Cin> I;P = new (nothrow) int [I];If (P = 0)Cout <"Error: Memory cocould not be allocated";Else{For (n = 0; n <I; n ++){Cout <"Enter number :";Cin> P [N];}Cout <"You have entered :";For (n = 0; n <I; n ++)Cout <p [N] <",";Delete [] P;}Return 0;} How many numbers wocould you like to type? 5Enter number: 75Enter number: 436Enter number: 1067Enter number: 8Enter number: 32You have entered: 75,436,106 7, 8, 32,
Note that NewThe value in the brackets of the statement is a variable ( I), Its value is input by the user, rather than a constant:
P = new (nothrow) int [I];

However, the user may input a value that is too big for our system, so that our system cannot process it. For example, when I try toHow many numbers(Number of digits)"Given a 1 billion value, my system cannot allocate so much memory for this program, and I get the text information we have prepared for this situation (Error: Memory cocould be allocated). Remember: when we try to allocate memory insteadNewSpecified in the expressionNothrowIn the case of a parameter, an exception may be thrown. If it is not processed, the program will be terminated.

It is a good habit to check whether a dynamic memory block is successfully allocated. Therefore, if you use NothrowMethod, you should always check the value of the pointer to be returned. Otherwise, use the exception method, although you have not handled this exception. In this way, the program will terminate at that point, instead of continuing to run the code that assumes that a piece of memory has been allocated but is not actually successful, causing unexpected results. In ANSI-C Dynamic Memory inThe new and delete operators are only in C ++. They are invalid in C language. However, the pure C language is used, and the dynamic memory is used through the functions malloc, calloc, realloc, and free. These functions are defined in the header file "cstdlib, since C ++ is a superset of C (which is not accurate-Translator's note), these functions are equally effective for C ++ programmers. The memory blocks allocated by these functions are incompatible with those returned by new. Therefore, each type needs to be manipulated by its own functions or operators.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.