HeapAlloc GlobalAlloc new等內存分配的區別

http://blog.sina.com.cn/s/blog_4bb59dc40100eaxz.html

 

GlobalAlloc是標準內存管理函數,標準內存管理函數都是操作進程的默認堆,所以這個函數是從進程的默認堆中分配內存空間,分配的空間可以是可移動的也可以是不可移動的。可移動的內存是指Windows在需要的時候可以將這個內存移動到另外一個地址.

 

關於GlobalAlloc and LocalAlloc,from MSDN  
   
  The global and local functions supported for porting from 16-bit code, or maintaining source code compatibility with 16-bit Windows. The global and local functions are slower   than other memory management functions and do not provide as many features. Therefore,  new   applications should use the heap functions.However, the global functions are still used with DDE and the clipboard functions.  
   
  Windows memory management does not provide a separate local heap and global heap, as 16-bit Windows does. As a result, there is no difference between the memory objects allocated by the GlobalAlloc and LocalAlloc functions. In addition, the change from a 16-bit segmented memory model to a 32-bit virtual memory model has made some of the related global and local functions and their options unnecessary or meaningless. For example, there are no longer near and far pointers, because both local and global allocations return 32-bit virtual addresses.
 
  Memory objects allocated by GlobalAlloc and LocalAlloc are in private, committed pages with read/write access that cannot be accessed by other processes. Memory allocated by using GlobalAlloc with GMEM_DDESHARE is not actually shared globally as it is in 16-bit Windows. This value has no effect and is available only for compatibility. Applications requiring shared memory for other purposes must use file-mapping objects. Multiple processes can map a view of the same file-mapping object to provide named shared memory. For more information, see File Mapping.

HeapAllock是堆管理函數,堆管理函數可以操作非默認堆(當然也可以操作默認堆),創建一個堆是用HeapCreate,這個函數返回一個堆句柄,然後可以用在HeapAllock函數中,即從返回的這個堆中申請內存空間,HeapAllock申請的內存只能是不可以移動的.

而new則是c++的標準函數,在Windows的VC++編譯器中,new在申請內存時最終調用的是GlabalAlloc,不過new還可以調用類的構造函數.

Windows的內存管理除了標準內存管理函數和堆管理函數之外,還有更加底層的虛擬內存管理函數,VirtualAlloc就是一個虛擬內存管理函數.

 

Personal Comprehension

GlobalAlloc分配的內存,還可以調用GlobalLock鎖定該內存塊(該函數可以被多次調用),在我們沒有調用GlobalUnlock之前,該內存塊會一直保持有效(即使調用了GlobalFree函數,但如果該內存的鎖計數不爲0,該內存塊也不會被釋放掉,依然保持有效)!而如果只調用一次delete,則使用new所分配的內存就會被釋放掉.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章