不得不說的故事 STL記憶體管理

2021-08-26 01:11:47 字數 1662 閱讀 1335

1. 概述

stl allocator是stl的記憶體管理器,也是最低調的部分之一,你可能使用了3年stl,但卻不知其為何物。

stl標準如下介紹allocator

the stl includes some low-level mechanisms for allocating and deallocating memory. allocators

are very specialized, and you can safely ignore them for almost all purposes.

allocators encapsulate allocation and deallocation of memory. they provide a low-level inte***ce that permits efficient allocation of many small objects; different allocator types represent different schemes for memory management.

allocator就在我們身邊,通常使用stl的方式:

#include

std::vectorarray(100);

本質上,呼叫的是:

#include

std::vectorstd::alloc

ator> array(100);

std::allocator就是乙個簡單的allocator

2. 為什麼需要了解allocator

專案中遇到的兩個case

1)memory高位

線上使用vector儲存待處理的資料,在停服務追資料的過程中,由於vector::clear並不釋放記憶體,造成記憶體始終處於高位。

參考:2)多執行緒使用vector、map

使用map儲存狀態,在多執行緒環境下,出現效能問題

在實際使用stl的過程中,會遇到很多問題,需要了解stl allocator

3. 使用

針對不同的應用場合,stl中實現了不同的allocator,如下(gcc-3.4:

例如,在多執行緒環境下,可以使用:

#include #include std::vector> array(100);

4.乙個簡單的allocator實現

我們可以實現自己的allocator

#include templateclass my_allocator : public std::allocator; // 記憶體的分配與釋放可以實現為自定義的演算法 pointer allocate(size_type count) void deallocate(pointer ptr, size_type count) // 建構函式 my_allocator() {} my_allocator(my_allocatorconst&) {} my_allocator& operator=(my_allocatorconst&) templatemy_allocator(my_allocatorconst&) {} templatemy_allocator& operator=(my_allocatorconst&) };

5. 參考文獻

stl原始碼剖析

ios icon 不得不說的故事

圖示是ios程式包所必需的組成部分。如果你沒有提供程式所需的各種尺寸的圖示,程式上傳發布時可能會無法通過驗證。ios程式為兼顧不同的應用場景,定義了多個不同規格的圖示,並以不同的命名區分 圖示名稱 大小圓角 用途必需 icon.png 57 x 57 10px 用於程式商店和在iphone ipod...

關於動態記憶體不得不說的故事

首先,會用到molloc語句,其實好多小夥伴都已經看出來了,沒錯這就是堆!下面先來介紹一下棧和堆的概念 1 棧 stack 有時候也叫 堆疊 區域性變數所在的記憶體區域,函式可以呼叫,window系統預設大小為1m 2 堆 heap 動態記憶體開闢區域,大小接近1.5g,使用時需要注意釋放記憶體。使...

RGBA 與 opacity不得不說的故事

css中rgba和opacity有著不同的使用情景和使用方法,但是有時候也有著相同的效果和功效,相同 都可以改變透明度,不同點 在mdn上opacity是這樣介紹的 當opacity屬性的值應用於某個元素上時,是把這個元素 包括它的內容 當成乙個整體看待,即使這個值沒有被子元素繼承。因此,乙個元素和...