每当我看到一个C“类”(任何用于访问以指向它的指针作为第一个参数的函数的结构)时,我都会看到它们的实现方式如下:
typedef struct
{
int member_a;
float member_b;
} CClass;
CClass* CClass_create();
void CClass_destroy(CClass *self);
void CClass_someFunction(CClass *self, ...);
...在本例中,CClass_create总是malloc的内存,并返回指向该内存的指针。
每当我看到new不必要地出现在C++上时,它通常看起来会让C++程序员发疯,但这种做法在C中似乎是可以接受的。为什么堆分配的结构“类”如此常见有什么原因吗?
发布于 2015-07-28 10:13:44
假设,就像在您的问题中一样,CClass_create和CClass_destroy使用malloc/free,那么对于我来说,以下操作是错误的做法:
void Myfunc()
{
CClass* myinstance = CClass_create();
...
CClass_destroy(myinstance);
}因为我们可以很容易地避免一个malloc和一个自由:
void Myfunc()
{
CClass myinstance; // no malloc needed here, myinstance is on the stack
CClass_Initialize(&myinstance);
...
CClass_Uninitialize(&myinstance);
// no free needed here because myinstance is on the stack
}使用
CClass* CClass_create()
{
CClass *self= malloc(sizeof(CClass));
CClass_Initialize(self);
return self;
}
void CClass_destroy(CClass *self);
{
CClass_Uninitialize(self);
free(self);
}
void CClass_Initialize(CClass *self)
{
// initialize stuff
...
}
void CClass_Uninitialize(CClass *self);
{
// uninitialize stuff
...
}在C++中,我们也宁愿这样做:
void Myfunc()
{
CClass myinstance;
...
}比这更重要:
void Myfunc()
{
CClass* myinstance = new CCLass;
...
delete myinstance;
}以避免不必要的new/delete。
https://stackoverflow.com/questions/31673065
复制相似问题