C ++ - dynamically allocated memory

 

0. Introduction

In C ++, the program memory space is divided into two parts, heap and stack.

Stack: All variables declared in a function are present in the stack.
Heap: program memory is not used for dynamic allocation of memory space in the program is running.
 
In C ++ applications and can be controlled by a new release of the memory space and delete operators.
 
new: apply for a period of memory space, and create an object, return to the starting memory address space.
delete: delete allocated memory space, prevent memory leaks.
 

1. new

 
new type_name
 
new application memory space may be any built-in data types, a structure may be defined, or from the class.
double * pvalue = NULL; // pointer is initialized to null 
pvalue = new double; // variable memory request

2. delete

When a dynamic application memory of the object is no longer used, the release of allocated memory space by delete.
delete pvalue; // release the memory pointed pvalue
 

3. dynamically allocated array

char * pvalue = NULL; // pointer is initialized to null 
pvalue = new char [20]; // variable memory request 
delete [] pvalue; // delete the array pointed pvalue
 
If it is a two-dimensional array
int ** array // assumed that the first dimension of the array length m, the second length dimension of the space dynamically allocated // n- 
Array = new new int * [m]; 
for (int I = 0; I <m; I ++) 
{ 
  Array [I] = new new int [n-]; 
} // release 
  for (int I = 0; I <m; I ++) 
 { 
  Delete [] arrary [I]; 
} 
Delete [] Array;

 

4. custom objects allocated memory space

#include <the iostream> 
the using namespace STD; 
 
class Box 
{ 
   public: 
      Box () { 
         COUT << "call the constructor!" << endl; 
      } 
      ~ Box () { 
         COUT << "call the destructor!" << endl ; 
      } 
}; 
 
int main () 
{ 
   Box * Box new new myBoxArray = [. 4]; 
 
   delete [] myBoxArray; // delete the array 
   return 0; 
}

  

 reference:

https://www.runoob.com/cplusplus/cpp-dynamic-memory.html

Guess you like

Origin www.cnblogs.com/east1203/p/11595151.html