C++內存管理筆記(一)內存分配概括

前言

根據侯捷大神的課所作的總結與實踐,主要是理清思路,方便之後查閱。

C++應用程序使用memory的途徑

在這裏插入圖片描述
如圖所示,C++應用程序可從四個層面來進行內存分配。

  • 使用C++標準庫所提供的內存分配管理器allocator
  • 使用C++基本函數new等
  • 使用C語言中的malloc/free
  • 調用操作系統內存分配的API

C++ memory primitives(內存分配基本工具)

在這裏插入圖片描述
test_primitives.h中使用了以上方法來分配內存.

#ifndef __TEST_PRIMITIVES_H__
#define __TEST_PRIMITIVES_H__

#include <iostream>
#include <complex>
#include <memory>   	 //std::allocator  
#include <ext/pool_allocator.h>	 //欲使用 std::allocator 以外的 allocator, 就得自行 #include <ext/...> 

using namespace std;

namespace memo_test
{
    void test_primitives()
    {
        cout << "\ntest_primitives().......... \n";
        //使用C函數 malloc 和 free 分配內存
        void* p1 = malloc(512);	//512 bytes
        free(p1);

        //使用C++表達式 new 和 delete 分配內存
        complex<int>* p2 = new complex<int>; //one object
        delete p2;             

        //使用 :: operator new 來分配內存
        void* p3 = ::operator new(512); //512 bytes
        ::operator delete(p3);

    //以下使用 C++ 標準庫提供的 allocators。來分配內存
    //其接口雖有標準規格,但實際廠商並未完全遵守;下面三者形式略有不同。
    #ifdef _MSC_VER
        //以下兩函數都是 non-static,定要通過 object 調用。以下分配 3 個 ints.
        int* p4 = allocator<int>().allocate(3, (int*)0); 
        allocator<int>().deallocate(p4,3);           
    #endif
    #ifdef __BORLANDC__
        //以下兩函數都是 non-static,定要通過 object 調用。以下分配 5 個 ints.
        int* p4 = allocator<int>().allocate(5);  
        allocator<int>().deallocate(p4,5);       
    #endif
    #ifdef __GNUC__
        //以下兩函數都是 static,可通過全名調用。以下分配 512 bytes.
        //void* p4 = alloc::allocate(512); 
        //alloc::deallocate(p4,512);   
        
        //以下兩函數都是 non-static,定要通過 object 調用。以下分配 7 個 ints.    
        void* p4 = allocator<int>().allocate(7); 
        allocator<int>().deallocate((int*)p4,7);     
        
        //以下兩函數都是 non-static,定要通過 object 調用。以下分配 9 個 ints.	
        //內存池分配方法
        void* p5 = __gnu_cxx::__pool_alloc<int>().allocate(9); 
        __gnu_cxx::__pool_alloc<int>().deallocate((int*)p5,9);	
    #endif
    }	
    } //namespace

#endif // !__TEST_PRIMITIVES_H__

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