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 use new and delete for dynamic memory allocation and array encapsulation in C++

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use new and delete for dynamic memory allocation and array encapsulation in C++". The content in the article is simple and clear, and it is easy to learn and understand. Please follow Xiaobian's train of thought to study and learn "how to use new and delete for dynamic memory allocation and array encapsulation in C++".

1. Use new to apply for memory

In some cases, the program can only determine the amount of memory required while it is running, and you should use new to request memory. If the application is successful, the first address will be returned. The applied memory can be accessed through the pointer to the first address. The syntax for applying for memory using new is as follows:

New data type (initialization parameter list)

The following example defines a pointer of type Duck, requests memory through new, and assigns the returned address to the pointer, as follows:

/ / 1. Pointer to define target type Duck * pointerDuck;/// 2, use new to request memory pointerDuck = new Duck; / / 3, use pointer to call object public member printf ("% d\ n", pointerDuck- > getAge ())

It should be noted that new returns an address, so you need to define a pointer to the target type in advance.

2. Use delete to free memory

Memory requested through new can only be released through delete. If not, it will cause a "memory leak". The syntax for using delete to free memory is as follows:

Delete pointer name; / example is as follows: delete pointerDuck

In addition, the destructor of the object (for custom types) is called when the delete statement is executed, and the same memory space can only be delete once. If the memory space is repeated delete, it will cause the program to run errors.

3. The initial value when using new to apply for memory

According to whether the object has a constructor, when new applies for memory, it can be divided into the following two cases according to whether the type has a constructor:

For objects with constructors, new executes the corresponding constructor

For basic data types that do not have a constructor, if you add () after the type name, 0 is used for initialization, but you cannot initialize with a specific value, and the type name is not initialized without (), but with random values.

Here is an example of using new for a basic data type without a constructor:

/ / if there are no parentheses after the type name, the random value pointer = new int [3]; / / if the type name is followed by parentheses, initialize pointer = new int [3] () with 0; 4. Use new and delete to request and free array space

For arrays, the syntax for dynamically requesting memory space using new is as follows:

New data type [array length]; / / the following pointer = new int [3] ()

The syntax for freeing memory using delete is as follows:

Delete [] pointer name; / / the following delete [] pointer;5, which encapsulates the array space applied for and freed by new with classes

Use the new application array, with the returned address as the value of the pointer. It is possible to use pointers to access arrays out of bounds, and it is not convenient to extend the functionality of arrays. The following is through custom classes to achieve functional extensions such as array element assignment and access, while solving the problem of array access out of bounds, as well as encapsulating the application and release of array space. The following step-by-step analysis of the coding process of an integer array:

(1) identify private data members: array size arraySize and array pointer pointerInt need to be declared as private data members

(2) determine the constructor: the constructor needs to use the array size arraySize, use new to apply for the array memory space of the corresponding length, and assign the returned address to the pointer pointerInt

(3) determine the destructor: the destructor needs to release the space applied for by pointerInt through delete.

(4) determine get and set functions: get and set functions need to perform "out of bounds check" and complete the function of taking elements and setting element values.

The following is the code for the implementation

Use new in class ArrayOfInt {public: / / constructor to apply for array space ArrayOfInt (int size): arraySize (size) {pointerInt = new int [arraySize] ();} / destructor completes array memory release ~ ArrayOfInt () {delete pointerInt;} / the set function sets the element value and checks void setElement (int index, int value) {assert (index > = 0 & & index)

< arraySize); *(pointerInt + index)=value; } /// get函数进行越界检查并返回指定位置的元素值 int getElement(int index) { assert(index >

= 0 & & index < arraySize); return * (pointerInt + index);} private: / Private data member is responsible for recording array length and first address int * pointerInt; int arraySize;}

Here is an example of using this array:

ArrayOfInt arrayOfInt (3); arrayOfInt.setElement (1666); printf ("% d\ n", arrayOfInt.getElement (1)); 6. Apply for a multidimensional array using new

First of all, it must be made clear that basic type pointers cannot be used for two-dimensional or higher-dimensional arrays, and the pointers defined below can only access one-dimensional arrays:

Int * pointer

In order to access an n-dimensional array, you must define an array of 1-dimensional pointers to nmi:

Int (* pointer) [2] [3]; / / Dimension [4] of the first dimension is not a pointer pointer = new int [4] [2] [3] () Thank you for reading, the above is the content of "how to use new and delete for dynamic memory allocation and array encapsulation in C++". After the study of this article, I believe you have a deeper understanding of how to use new and delete for dynamic memory allocation and array encapsulation in C++. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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