如果我有一個生產者/消費者設置,其中要生成大量對象並將其組裝成UDP數據報,發送一個塊(而不是每個對象發送一個非常小的數據報),我想問一些關於不同策略的建議,以避免在產生/消耗時持續分配/釋放對象。嵌入式C++:如何使用容器/數組在堆棧上回收變量與堆上的動態分配
該軟件是在嵌入式系統上運行的,所以我對一種策略感興趣,該策略會在系統啓動時在堆棧中分配大量對象,而不是程序執行期間的堆。我正在考慮以下內容,但歡迎提供建議/想法/批評。我提議合理嗎? (下面的僞代碼)。
class SmallCommonObject {
// some sort of members here
int member;
};
SmallCommonObject arrayOfObjects[MAX_ARRAY_SIZE];
// this is a collection of pointers to objects that are not in use
vector<SmallCommonObject*> unusedObjects;
// here we store pointers to objects that are in use
vector<SmallCommonObject*> objectsBeingUsed;
// initially store all objects in unused collection
for (int i = 0; i < MAX_ARRAY_SIZE; i++)
unusedObjects.push_back(&arrayOfObjects[i]);
// if unusedObjects is not empty, we can use thus:
SmallCommonObject *object = &unusedObjects.back();
unusedObjects.pop_back();
object->member = SOME_VALUE;
// save into used container
objectsBeingUsed.push_back(object);
// repeat above as required
// now do something with the vector of objects that are in use
// when complete
for (int i = 0; i < objectsBeingUsed.size(); i++) {
SmallCommonObject *object = &objectsBeingUsed.back();
objectsBeingUsed.pop_back();
unusedObjects.push_back(object);
}
我的容器選擇怎麼樣,他們是最佳的?在運行時
我認爲你正在尋找對象池http://gameprogrammingpatterns.com/object-pool.html(搜索它,許多解決方案在線) – AlexanderBrevig 2014-08-28 19:16:06
我會添加儲備調用向量 – programmerjake 2014-08-28 22:26:17