-->

实例化与自定义分配器类在共享存储器中(Instantiating class with custom

2019-10-20 08:11发布

我拉我的头发由于下面的问题:我下面的例子 Boost.Interprocess中文档中给出的实例,我在共享内存中写了一个固定大小的环形缓冲区缓存类。 我的课的骨架构造函数是:

template<typename ItemType, class Allocator >
SharedMemoryBuffer<ItemType, Allocator>::SharedMemoryBuffer( unsigned long capacity ){

    m_capacity = capacity;

    // Create the buffer nodes.
    m_start_ptr = this->allocator->allocate();  // allocate first buffer node
    BufferNode* ptr = m_start_ptr;
    for( int i = 0 ; i < this->capacity()-1; i++ ) {
        BufferNode* p = this->allocator->allocate();    // allocate a buffer node
    }
}

我的第一个问题:请问这种分配保证缓冲区节点在连续存储单元,即分配的,当我尝试从地址的第n个节点m_start_ptr + n*sizeof(BufferNode)在我的Read()方法将它工作? 如果不是,有什么更好的办法来保持节点,创建一个链表?

我的测试工具如下:

// Define an STL compatible allocator of ints that allocates from the managed_shared_memory.
// This allocator will allow placing containers in the segment
typedef allocator<int, managed_shared_memory::segment_manager>  ShmemAllocator;

//Alias a vector that uses the previous STL-like allocator so that allocates
//its values from the segment
typedef SharedMemoryBuffer<int, ShmemAllocator> MyBuf;

int main(int argc, char *argv[]) 
{
    shared_memory_object::remove("MySharedMemory");

    //Create a new segment with given name and size
    managed_shared_memory segment(create_only, "MySharedMemory", 65536);

    //Initialize shared memory STL-compatible allocator
    const ShmemAllocator alloc_inst (segment.get_segment_manager());

    //Construct a buffer named "MyBuffer" in shared memory with argument alloc_inst
    MyBuf *pBuf = segment.construct<MyBuf>("MyBuffer")(100, alloc_inst);
}

这给了我各种有关模板的最后一条语句编译错误。 我究竟做错了什么? 是segment.construct<MyBuf>("MyBuffer")(100, alloc_inst)提供两个模板参数的正确方法?

Answer 1:

我的第一个问题:请问这种分配保证缓冲区节点在连续存储单元,即分配的,当我尝试访问从地址m_start_ptr + N *的sizeof(BufferNode)的第n个节点在我的Read()方法将它工作?

号的原因是,你只需要在第一个节点。 所有BufferNode您创建的没有被保存(比如说,在链表的方式),并有助于内存泄漏的对象。 此外,这种风格的分配不出示担保连续的存储单元。 随机访问(如你的国家,你的问题后)很可能会失败。 为了得到连续的内存,你需要创建数组(可能是动态) BufferNode对象。

这给了我各种有关模板的最后一条语句编译错误。 我究竟做错了什么?

很难说在不知道实际的错误。 另外,你是否了解你的代码(以及如何Boost::Interprocess配合或如何分配工作)?

请注意,您举的例子创建一个vector这是保证有连续的存储器,用于其包含的对象。 这里唯一的区别是,在一个共享内存段,而不是自由存储这就是通常发生在你没有指定一个allocator作为第二个参数,并使用一个默认创建的对象。



文章来源: Instantiating class with custom allocator in shared memory