1

如果我想从函数返回一个指针,什么会更好更安全?

void pro_register_application(WNDCLASS* wc); /* use wc in function */

或者

WNDCLASS* pro_register_application(void)
{
   WNDCLASS* wc = malloc( sizeof(WNDCLASS) );
   ...
   return wc;
}
4

2 回答 2

3

只要您适当地记录正在处理的缓冲区所有权的详细信息,两者都是相同的,选择哪一个取决于选择的问题。

需要清楚地告知第二个示例的用户缓冲区的所有权已转移给他们,因此释放缓冲区的责任也是如此。

于 2012-04-19T16:00:59.600 回答
1

If you choose to have your function create a data structure and return a pointer (your second way, up there), the caller has to know HOW you allocated the space for it... did you use malloc(), or GlobalAlloc(), or some other mechanism?... and then use the corresponding method to get rid of the thing. That's sufficient reason to make the client allocate the space and pass in a pointer, to my mind.

That said, I wouldn't kill anybody for using either method, if they'd taken appropriate care to deallocate the memory correctly.

This is one of the reasons that COM objects are useful-- the client doesn't have to know how an object was created, it just has to call Release() when it's done.

于 2012-04-19T16:09:42.270 回答