自定义(池)分配与升压shared_ptr的 [英] Custom (pool) allocator with boost shared_ptr

查看:83
本文介绍了自定义(池)分配与升压shared_ptr的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个shared_ptr管理的对象从池中分配,说Boost的游泳池界面,如何才能实现这一目标?

I want objects managed by a shared_ptr to be allocated from a pool, say Boost's Pool interface, how can this be achieved?

推荐答案

这里的code做你想要什么(可能将无法编译,因为我不手头上提升,我从写它内存):

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):

class YourClass; // your data type, defined somewhere else

boost::object_pool<YourClass> allocator;

void destroy(YourClass* pointer)
{
    allocator.destroy(pointer);
}

boost::shared_ptr<YourClass> create()
{
    // usage of object_pool<??>::construct requires that you have a 
    // YourClass::YourClass(void) defined. If you need to pass arguments
    // to the new instance, you need to do that separately.
    // 
    // for example using a YourClass::Initialize(your,parameters,here) method
    // before returning from this function
    return boost::shared_ptr<YourClass>( allocator.construct(), &destroy );
}

// usage:
boost::shared_ptr<YourClass>  newObject = create();

我实现这两次,在两个不同的项目。在这两种中,创建和删除功能是同步的(你可以添加周围使用分配器的的boost ::互斥锁),他们是一个工厂类的成员(和摧毁的签名被修改为无效(YourClass *)升压的用法: :绑定

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 the destroy's signature was modified to void (YourClass*) through the usage of boost::bind).

您也可以通过绑定摧毁和创建) > object_pool&LT; YourClass方式&gt; ::摧毁 dirrectly在boost :: shared_ptr的构造

You can also avoid writing two extra functions (the destroy and create) by binding object_pool<YourClass>::destroy dirrectly in the boost::shared_ptr constructor.

我现在懒得写所有:)

修改(感动我的答案评论这里为code格式):

Edit (moved my answer comment in here for the code formatting):

要绑定的破坏功能:

class ClassFactory
{
    boost::object_pool<YourClass> allocator;
public:
    boost::shared_ptr<YourClass> create()
    {
        return boost::shared_ptr<YourClass>(
            allocator.construct(),
            boost::bind(&ClassFactory::destroy, this, _1) );
    }

    void destroy(YourClass* pointer)
    {
        allocator.destroy(pointer);
    }
};

的ClassFactory 应比的shared_ptr (如的ClassFactory 实例被删除,this指针传递给的shared_ptr 实例将是无效的 - 而崩溃您的应用程序时,的shared_ptr 删除 YourClass 实例)。

ClassFactory should have a longer lifetime than the shared_ptr (if the ClassFactory instance is deleted, the this pointer passed to the shared_ptr instance will be invalid - and crash your app when the shared_ptr deletes the YourClass instance).

这篇关于自定义(池)分配与升压shared_ptr的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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