带有 boost shared_ptr 的自定义(池)分配器
我希望从池中分配由shared_ptr管理的对象,比如说Boost的Pool接口,这如何实现?
I want objects managed by a shared_ptr to be allocated from a pool, say Boost's Pool interface, how can this be achieved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是执行您想要的操作的代码(可能无法编译,因为我手头没有 boost 并且我是从内存中编写的):
我在两个不同的项目中实现了两次。在这两个函数中,创建和销毁函数都是同步的(您可以在分配器的使用周围添加一个 boost::mutex 锁),并且它们是工厂类的成员(并且销毁函数code> 的签名通过使用
boost::bind
修改为void (YourClass*)
。您还可以通过直接在 boost:: 中绑定
object_pool::destroy
来避免编写两个额外的函数(destroy
和create
)。 Shared_ptr 构造函数。我现在懒得写这些了:)。
编辑(将我的答案注释移到此处以进行代码格式化):
要绑定销毁函数:
ClassFactory
应该比shared_ptr
有更长的生命周期(如果ClassFactory
实例被删除,则传递给shared_ptr
实例的 this 指针将无效 - 并且当shared_ptr
删除该实例时,您的应用程序会崩溃YourClass
实例)。Here's the code to do what you want (probably won't compile as I don't have boost on hand and I'm writing it from memory):
I implemented this twice, in two different projects. In both, the create and destroy functions were synchronized (you can add a
boost::mutex
lock around the use of allocator) and they were members of a factory class (and thedestroy
's signature was modified tovoid (YourClass*)
through the usage ofboost::bind
).You can also avoid writing two extra functions (the
destroy
andcreate
) by bindingobject_pool<YourClass>::destroy
dirrectly in the boost::shared_ptr constructor.I'm too lazy to write all that now :).
Edit (moved my answer comment in here for the code formatting):
To bind the destroy function:
ClassFactory
should have a longer lifetime than theshared_ptr
(if theClassFactory
instance is deleted, the this pointer passed to theshared_ptr
instance will be invalid - and crash your app when theshared_ptr
deletes theYourClass
instance).明显的解决方案:
创建您自己的
make_shared
函数并强制使用此方法来创建shared_ptr
。凡违反本规则者,将受到惩罚。注意:
似乎对
shared_ptr
的作用感到困惑。它的作用是管理您分配的内存,但是要做到这一点,它需要对其自己进行一些分配(计数器和删除器),因此您可以为其传递一个分配器。Evident solution:
Create your own
make_shared
function and enforce the use of this method to createdshared_ptr
. Those who derive from The Rule shall be punished.Note:
There seems to be a confusion with the role of the
shared_ptr
. Its role is to manage memory than YOU have allocated, however to do so it requires some allocation of its own (counter and deleter), thus you may pass it an allocator for those.这些几乎是正交的问题。
shared_ptr
不参与对象的分配。它所关注的是不再引用的内存的删除。如果您从默认堆以外的任何位置进行分配,则需要提供自定义删除器
These are almost orthogonal concerns.
shared_ptr
plays no part in allocation of objects.Where it is concerned is in the deletion of memory no longer referenced. If you have allocated from anything other than the default heap you'll need to provide a custom deleter