它是不礼貌的从函数返回指针分配堆? [英] Is it bad manners to return a heap allocated pointer from a function?
问题描述
在的boost :: shared_ptr的
,是它认为是不好的做法,从函数返回指针分配堆,因为调用者将被要求记住免费()
的对象?
Before boost::shared_ptr
, was it considered a bad practice to return a heap allocated pointer from a function, since the caller will be required to remember to free()
that object?
或者,是它认为正常?
推荐答案
我不认为这是不好的做法,只要你的API还提供了一个等效 XXX_free
(或 XXX_close
, XXX_clearup
,或其他)功能,即客户端code可当指针完成调用
I don't consider it bad practice, so long as your API also provides an equivalent XXX_free
(or XXX_close
, XXX_clearup
, or whatever) function, that the client code can call when finished with the pointer.
这样的话,你有一个一致的,对称的API,在这个意义上,对于堆对象的生命周期责任保持在同一个地方。
That way, you have a consistent, symmetrical API, in the sense that responsibility for the lifetime of a heap object is maintained in one place.
这方法也适合于更复杂的资源释放。例如,如果被返回的指针是到动态分配的结构,在又具有指向动态分配的存储器件,整个清理过程可以隐藏/从客户端code抽象
This approach is also amenable to more-complex resource freeing. For example, if the pointer that gets returned is to a dynamically-allocated struct that in turn has members that point to dynamically-allocated memory, the entire cleanup procedure can be hidden/abstracted from the client code.
这篇关于它是不礼貌的从函数返回指针分配堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!