在哪里删除工厂创建的对象? [英] Where to delete an object created by factory?

查看:142
本文介绍了在哪里删除工厂创建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个工厂,创建一个对象并返回一个指针,它会是一个更好的方式来删除它:

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

delete 在用户代码中调用,或者通过一个新的 DestructObject 函数,

By delete call in the "user" code, or by a new DestructObject function which I should have together with the factory?

推荐答案

在一般情况下,工厂可能不使用纯旧 new 目的。它可以使用放置 new 的对象和/或页面池, malloc ,或者更奇怪的内存映射)。有至少三种方法来处理这个问题,我可以想到:

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. 让工厂提供 recycle 方法。

  2. 返回一个智能指针,知道如果没有查询器保留,如何删除该对象。

  3. 在对象本身中实现自定义删除运算符。

  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.


$ b b我不犹豫的推荐一个在另一个,因为我没有给予足够的思想在最后五分钟提供一个确定的意见,但我倾向于喜欢最后一个选项结合一个常规的智能指针,如boost / tr1 :: shared_ptr。

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.

这篇关于在哪里删除工厂创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆