[英]cpp - representing an array of variable-sized static stack based arrays
我想創建一個 static 結構實例數組,它有一個成員——指向一個 static 基於堆棧的可變大小字節數組。 (可以表示為數組)
由於數組的大小以及它包含 static 數據的事實——我想避免堆分配並保持數據基於堆棧。
一個具體的例子:
struct DataBlock
{
size_t id;
const unsigned char* data;
};
void test()
{
// creating an array of DataBlock, with static data of different size
DataBlock dataArray [] = {
{
.id = 1;
.data = {0xFF, 0xCC, 0XDD};
},
{
.id = 1;
.data = {0xFF};
}
};
}
如果數據大小相同,我可以像那樣定義data
成員——
const unsigned char data[STATIC_SIZE];
但由於每個成員的長度可能不同,因此這種方法無關緊要。
一個明顯的解決方案是用std::vector
替換data
——但同樣,我想避免堆分配,因為數據是 100% static 並且在編譯時已知。
我探索了一些基於模板的解決方案——最終為每個數組大小生成一個單獨的 function,這也不是期望的結果。
我確定 C++ 有針對這種情況的解決方案。
嘗試避免在動態 memory(“堆”)中進行多余分配的沖動是好的,但在這種情況下會導致問題。 首先,C++ 沒有可變大小的 arrays。其次,如果您想在創建它的 function 之外使用它,它將不再存在。 但最重要的是,第三,如果您的數據確實非常大,將其放入自動存儲中將填滿典型進程運行的微小堆棧空間。
所以,如果我對你的理解正確的話,你有大量的DataBlock
對象,每個對象可能包含少量數據項。 那么妥協就是
std::vector
,因為這會創建很多小的動態 memory 分配。 而是分配一個大的std::vector
並讓您的數據項攜帶指向該向量的迭代器對。也許你會 go 這樣的事情:
using DataBlock = std::pair<std::vector<unsigned char>::const_iterator>;
template <std::size_t N>
struct DataBlocks {
std::vector<unsigned char> data;
DataBlock array[N];
};
auto makeDataBlocks() {
// return std::unique_ptr<DataBlocks<N>> for some N
}
您可以將所有數據一起存儲在一個數組中,該數組的大小至少需要是所有數據的總大小。 為此,我們有一個助手 class:
struct Data {
static const int MAX_SIZE = 100;
uint8_t data[MAX_SIZE];
int index = 0;
const uint8_t* initBlock(const std::vector<uint8_t>& src) {
int at = index;
for (auto x: src) {
data[index++] = x;
}
return data + at;
}
};
然后只需調用initBlock
方法將一些數據放入該數組並獲得指向數據的指針:
void test()
{
Data data;
// creating an array of DataBlock, with static data of different size
DataBlock dataArray [] = {
{
.id = 1,
.data = data.initBlock({0xFF, 0xCC, 0XDD})
},
{
.id = 1,
.data = data.initBlock({0xFF})
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.