delete point to note when c ++ dynamically allocated memory

delete given delete [] Ku别:

1, the use of new distribution for simple regardless of the type is an array or non-array of memory space can be used in two ways, such as:

int *a = new int[10];   
delete a;   
delete [] a;

Same release effect in this case due to: allocate simple type of memory, the memory size has been determined, the memory system can be managed and, on destruction, the system does not call the destructor, it may be obtained directly by the pointer actually allocated memory space, even if it is a memory array (memory allocation system will record the size and other information during dispensing, this information is stored in the structure _CrtMemBlockHeader, the situation can be found in the VC installation directory CRT \ SRC \ DBGDEL .cpp)

2, for the class Class, reflecting the specific differences in two ways

When you assign an array of objects of a class in the following ways:

class A 
{ 
    Private :
         char * m_cBuffer;
         int m_nLen;
     public : 
        A () {m_cBuffer = new new  char [m_nLen];}
         ~ A () { Delete [] m_cBuffer;} 
}; 
A * A = new new A [ 10 ]; 

// only release all the memory space a pointer, but only calls the destructor a [0] from the rest of the object a [1] to a [. 9] nine user-allocated memory space corresponding to m_cBuffer can not be released to a memory leak 
Delete a; 

// call the object using the class destructor frees users are assigned their own memory space and a memory space, releasing all pointer 
Delete [] a;

So summarize that, if the memory address of the memory space ptr represents a new application with the return of the so-called pointer, then:

  •  ptr the Delete  - used to free memory on behalf of, and only used to release the memory pointed to by ptr.
  •  the Delete [] rg  - rg for release at the memory,! ! Also call one by one for each object in the array destructor! !

For simple data like int / char / long / int * / struct type and so on, because the object is no destructor, so use the delete and delete [] is the same! But if C ++ is an array of objects is different!

Guess you like

Origin www.cnblogs.com/cqu-qxl/p/11485102.html