我被赋予了实现以下C
功能的任务,该功能实现了C vector
:
40 CVector *CVectorCreate(int elemSize, int capacityHint, CVectorCleanupElemFn fn)
41 {
42 //allocate a new CVector struct
43 CVector *cvector = (CVector*)calloc(1, sizeof(CVector));
44 assert(cvector != NULL);
45 //allocate space for the buffer
46 cvector->vector = calloc(capacityHint, elemSize);
47 assert(cvector->vector != NULL);
48 /*
49 * Use these in other to make the code more efficient
50 * and also there is going to have less coding in other to
51 * perform the same operation
52 * I'm also going to explicity initialize all the members of
53 * vector even though I don't need
54 */
55 cvector->capacity = capacityHint;
56 cvector->elemSize = elemSize;
57 cvector->head = cvector->tail = 0;
58 return cvector;
59 }
我还定义CVector
为以下结构:
17 typedef struct CVectorImplementation {
18 // include your desired fields here
19 int head;
20 int tail;
21 int numElements;
22 int capacity;
23 int elemSize;
24 void* vector;
25 }CVector;
但是,在函数的头部CVectorCreate
,有CVectorCleanupElemFn
一个我想是用于使用智能指针的,但我不确定如何在我的结构中包含/使用该函数。请有更多经验的人告诉我它的目的是什么CVectorCleanupElemFn
以及我该如何使用它?我还有以下功能(提莫的建议到位):
63 void CVectorDispose(CVector *cv)
64 {
65 assert(cv != NULL);
66 // I would imagine cleanUp holds the function
67 // that empties the buffer
68 int index = cv->head;
69 while(index <= tail) {
70 (cv->cleanupFn)(cv->vector[index]);
++index;
71 }
72 free(cv->vector);
73 // finally free the struct cv
74 free(cv);
75 }
我试图弄清楚如何将它们绑定在一起。