[英]C queue implementation using void* - good or bad practice?
我使用void指針在C中實現了一個基本的隊列結構。 程序如下:
memcpy()
它有一個本地副本。 結構本身看起來像這樣:
struct queue
{
void* start; //pointer to the beginning of queue
void* end; //-||- to the end
size_t memsize; //size of allocated memory, in bytes
size_t varsize; //size of a single variable, in bytes
void* initial_pointer; //position of the start pointer before pop() operations
};
start和end只是指向當前分配的內存塊中某個位置的void指針。 如果我在隊列上推送元素,我會通過varsize
遞增結束指針。 如果我pop(),我只是通過varsize
減少結束指針。
我不認為我應該在這里發布功能代碼,它超過100行。
問題:這被認為是好的還是壞的做法? 為什么不)?
注意:我知道C中的隊列還有很多其他選項。我只是詢問這個的質量。
編輯:可以在這里獲得實現:http:// 89.70.149.19 /stuff/queue.txt(刪除空格)
如果您不知道要存儲在隊列中的對象的類型和大小,則可以使用void *
(實際上,C標准庫遵循相同的方法,請參閱memcpy()
和qsort()
函數例子)。 但是,最好使用size_t
(如果需要簽名數據類型,則使用ssize_t
)來指定存儲在隊列中的元素的大小。
你真的沒有給我們足夠的信息來確定你的實現。 void*
對於用戶數據項是好的,否則在C中你做不了多少。
但我強烈懷疑你有一個內部列表元素類型,用於管理單個項目,如
struct list_item {
struct list_item* next;
void* data;
};
如果是這種情況,並且您的start
和end
指針指向這些元素,那么您最終應該在struct queue
聲明中使用您的元素類型:
struct queue
{
struct list_item* start; //pointer to the beginning of queue
struct list_item* end; //-||- to the end
size_t memsize; //size of allocated memory, in bytes
size_t varsize; //size of a single variable, in bytes
struct list_item* initial_pointer; //position of the start pointer before pop() operations
};
為此,您甚至不必將struct list_item
的定義暴露給struct queue
的用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.