C 物件池實現

2021-07-08 18:37:19 字數 1076 閱讀 8261

在實際中,我們會遇到乙個類最多隻允許若干個物件同時存在的情形。如果這個類的物件會被頻繁的建立,使用並銷毀,那這時會對系統效能造成影響,而這時可以考慮使用物件池的方法來避免每次使用物件都需要從「構造->使用->銷毀」這個流程,物件池中的每個物件都一次構造多次使用,而析構也只會在物件池析構是才會發生。

要實現物件池,那關鍵問題就在於如果在物件析構時不是真正的析構,而是重新回到物件池中。假如我們每次從物件池中取到的物件都是物件本身,那我們則無法讓物件在需要析構時重新回到物件池,所以我們只能返回乙個管理物件,這個管理物件實際管理者我們的實際物件,在它析構時它將實際的物件歸還到物件池中。那最好的選擇就是每次都返回乙個只能指標比如std::unique_ptr,我們在返回這個只能指標時,將其析構函式修改為將物件歸還至物件池,而非直接析構,這樣就可以實現物件**了。下面來直接看**:

#pragma once

#include #include #include #include using std::unique_ptr;

using std::vector;

using std::function;

using std::mutex;

templateclass objectpool

unique_ptrget()

);objcont.pop_back();

return objptr;

}

bool hasmoreobject() const

size_t objectsremained() const

private:

vector> objcont;

static std::mutex objobtainlock;

};templatestd::mutex objectpool::objobtainlock;

在使用這個物件池時,我們在需要使用物件池的類中提供乙個介面來獲取這個類的物件池,並且在初始化時,將指定數量的物件加入物件池中。

最後要說明的是,使用物件池有乙個問題即一旦物件池建立了,那只有當程式結束之後,物件池所占用的空間才能夠被釋放,所以在使用時需要考慮到這一點。

物件池的c 實現

作用 物件池是用於管理和 物件的,物件池適合緩解大的物件的頻繁申請和釋放問題。實現如下 title object pool.desc 物件池,以池化的思想來減少物件的申請和釋放操作.author gdl.version 0.0.1 date 2019.10.15 22 43 modify date ...

c 物件池的實現

ifndef cellobjectpool hpp define cellobjectpool hpp include include include ifdef debug ifndef xprintf include define xprintf printf va args endif els...

c 模擬實現物件池

怪物基類 pragma once 怪物列舉 enum monstertype class monster virtual monster 虛析構 monstertype gettype const private monstertype type 怪物型別 三個子類怪物 pragma once in...