C++中的記憶體配置

來源:互聯網
上載者:User

標籤:

C++提供下面兩種方法分配和釋放未構造的原始記憶體(1)allocator 類,它提供可感知類型的記憶體配置(2)標準庫中的 operator new 和 operator delete,它們分配和釋放需要大小的原始未類型化的記憶體 C++ 還提供不同的方法在原始記憶體中構造和撤銷對象(1)std::allocator<T>::construct 在未構造記憶體中初始化對象,std::allocator<T>::destroy 在對象上運行適當的解構函式。(2)定位 new 運算式( placement new expression),接受指向未構造記憶體的指標,並在該空間中初始化一個對象或一個數組。(3)直接調用解構函式來撤銷對象(4)演算法 uninitialized_fill 和 uninitialized_copy 像 fill 演算法和 copy 演算法一樣執行,除了它們在目的地構造對象而不給對象賦值之外。std::allocator<T>allocator類將記憶體的分配及物件建構分開。分配及釋放分別是 allocate 和 deallocate 。構造和析構分別是 construct 和 destroy。std::vector<T>標準庫中的 vector 是一個動態數組。在使用時,vector 預先分配一塊記憶體,當資料增長到預先分配的記憶體不夠使用時,vector 採取的策略是重新分配 2 倍於當前 vector 容量大小的記憶體,並把所有資料複製到新地址處,舊地址所有資料進行析構,最後將這塊舊的記憶體釋放。
  1.  1 template<class T> 2 classvector 3 { 4 public: 5        vector():elements(0),first_free(0),end(0){} 6        void push_back(const T&); 7        //… 8 private: 9        static std::allocator<T> alloc;10        void reallocate();11        T* elements;12        T* first_free;13        T* end;14        //…15 };

elements 指向數組的第一個元素,first_free 指向第一個閒置位置,end 指向數組最一個元素的下一個元素。std::vector<T>::push_back(const T& t)
  1.  1 tmplate <class T> 2 voidvector<T>::push_back(const T& t) 3 { 4     //are we out of space 5     if(first_free == end) 6         reallocate();// gets more space and copies existing elements to it 7     alloc.construct(first_free,t); 8     ++first_free; 9 }10 tmplate <class T>11 voidvector<T>::reallocate()12 {13     std::ptrdiff_t size = first_free – elements;14     std::ptrdiff_t newcapacity =2* max(size,1);15  16     T* newelements = alloc.allocate(newcapacity);17  18     uninitialized_copy(elements,first_free,newelements);19  20     for(T *p = first_free; p != elements;}21         alloc.destroy(--p);22  23     if(elements)24         alloc.deallocate(elements,end-elements);25     elements = newelements;26     first_free = elements + size;27     end = elements + newcapacity;28 }

     

 operator new 函數和 operator delete 函數 理解 new 運算式
  1. 1 //new expression2 string *sp =new string(“initialized”);

    首先,該運算式調用名為 operator new 的標準庫函數,分配足夠大的原始的未類型化的記憶體;

接下來,運行該類型的一個建構函式,用指定初始化式構造對象;最後,返回指向新分配並構造的對象的指標 
  1. 1 delete sp;

    首先,對 sp 指向的對象運行適當的解構函式;

然後,通過調用名為 operator delete 的標準庫函數釋放該對象所用記憶體 operator new 和 operator delete 介面
  1. 1 void*operator new(size_t);2 void*operator new[](size_t);3 void*operator new(std::size_t size,void* ptr)throw();//placement4  5 void*operator delete(void*);6 void*operator delete[](void*);

     

與 allocator 類的 allocate 和 deallocate 成員類似。 但是,operator new 和 operator delete 在 void* 指標而不是類型化的指標上進行操作。這就意味著,allocate 成員配置類型化的記憶體,不必計算以位元組為單位的所需記憶體量,它們也可以避免對 operator new 的傳回值進行強制類型轉換 placement new 定位 new 運算式 placement new 在已指派的原始記憶體中初始化一個對象。它與 new 的其它版本的不同之處在於,它不分配記憶體。 定位 new 運算式的形式是:new (place_address) typenew (place_address) type (initializer-list) 例:
  1. 1 std::allocator<std::string> alloc;2 string *sp = alloc.allocate(2);// allocate space to hold 2 strings3 new(sp) string(b,e);4 alloc.construct(sp +1, string(b,e));

     

總結 類特定的 new 和 delete預設情況下, new 運算式通過調用由標準庫定義的 operator new 版本分配記憶體。通過定義自己的名為 operator new 和 operator delete 的成員,類可以管理用於自身類型的記憶體。 編譯器看到類類型的 new 或 delete 運算式的時候,它查看該類是否有 operator new 或  operator delete 成員,如果類定義(或者繼承)了自己的成員 new 和 delete 函數,則使用那些函數為對象分配和釋放記憶體;否則,調用這些函數的標準庫版本。 一個記憶體 Clerk基類通用策略:預先分配一塊原始記憶體來儲存未構造的對象,建立新元素時,可以在一個預先分配的對象中構造;釋放元素的時候,將它們放回預先指派至的塊中,而不是將記憶體實際返回給作業系統。 這種策略常被稱為維持一個自由列表(freelist)。可以將自由列表實現為已指派但未構造的對象的鏈表。 
  1.  1 template<class T> 2 classCachedObj 3 { 4 public: 5            void*operatornew(std::size_t); 6            void*operatordelete(void*, std::size_t); 7            virtual~CachedObj(){} 8 protected: 9            T* next;10 private:11            staticvoid add_to_freelist(T*);12            static std::allocator<T> alloc_mem;13            static T* freeStore;14            staticconst std::size_t chunk;15 }

     

CacheObj 只是分配和管理已指派但未構造對象的自由列表。 定義 operator new,返回自由列表的下一個元素,並將該元素從自由列表中刪除。當自由列表為空白的時候,operator new 將分配新的原始記憶體。定義 operator delete,在撤銷對象時將元素放回自由列表。 實現:
  1.  1 template<class T> 2 void*CachedObj<T>::operatornew(size_t sz) 3 { 4     if(sz !=sizeof(T))  returnnullptr; 5     if(!freeStore) 6     { 7           T* array = alloc_mem.allocate(chunk); 8            for(size_t i =0; I != chunk;++i) 9                      add_to_freelist(&array[i]);10      }11      T*p = freeStore;12      freeStore = freeSore->CachedObj<T>::next;13      return p;14 }15 template<class T>16 voidCachedObj<T>::add_to_freelist(T*p)17 {18    p->CachedObj<T>::next = freeStore;19    freeStore = p;20 }21 template<class T>22 voidCachedObj<T>::operatordelete(void*p)23 {24     if(p !=0)25            add_to_freelist(static_cast<T*>(p));26 }

     

 CachedObj 其實很像 linux 的鏈表。除掉 private 的 static 變數和一個虛表的指標,CachedObj 其實只維護一個 T* next。它的記憶體布局像這樣:當繼承 CachedObj 類的時候,用來執行個體化 CachedObj 類的模板類型將是衍生類別型本身。 其實就是利用模板很巧妙地把 next 指標的類型設定成子類的類型。執行個體化出來的類彷彿本就是一個類,沒有兩個類拼湊的感覺,天衣無縫。  例如:
  1. 1 template<classType>2 classQueueItem:3 publicCachedObj<QueueItem<Type>>{};

     

QueueItem 繼承自 CachedObj,它的記憶體布局類似這樣:



來自為知筆記(Wiz)



C++中的記憶體配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.