自定义(池)分配器与boost shared_ptr

mya*_*hya 26 c++ boost shared-ptr allocator

我希望从一个池分配一个shared_ptr管理的对象,比如Boost的Pool接口,怎么能实现呢?

utn*_*tim 21

这里是你想做的事情的代码(可能不会编译,因为我手头没有提升,而是从内存中编写):

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();
Run Code Online (Sandbox Code Playgroud)

我在两个不同的项目中实施了两次.在两者中,create和destroy函数都是同步的(你可以boost::mutex使用allocator 添加一个锁),它们是工厂类的成员(并且通过使用destroy修改了它的签名).void (YourClass*)boost::bind

您还可以通过在boost :: shared_ptr构造函数中直接绑定来避免编写两个额外函数(destroycreate)object_pool<YourClass>::destroy.

我现在懒得写所有这些:).

编辑(在此处移动我的答案评论以进行代码格式化):

绑定destroy函数:

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

ClassFactory应该具有比生命周期更长的生命周期shared_ptr(如果ClassFactory实例被删除,传递给shared_ptr实例的this指针将无效 - 并在shared_ptr删除YourClass实例时使应用程序崩溃).