Where to delete an object created by factory?

后端 未结 4 931
萌比男神i
萌比男神i 2021-02-19 04:01

If I have a factory, that creates an object and returns a pointer to it, what will be a better way to delete it:

By delete call in the \"user\" code, or by

4条回答
  •  野的像风
    2021-02-19 04:15

    In the general case, the factory might not use plain old new to allocate the object. It may use object and/or page pooling, malloc with placement new, or something even more exotic (memory mapping?). There are at least three ways to handle this that I can think of:

    1. Have the factory supply a recycle method to be called when you are done with the object.
    2. Return a smart pointer that knows how to do away with the object once no referers remain.
    3. Implement a custom delete operator in the object itself.

    I hesitate to recommend one over the other, since I haven't given it enough thought in the last five minutes to proffer a definitive opinion, but I would tend to favour the last option in combination with a regular smart pointer like boost/tr1::shared_ptr.

提交回复
热议问题