我拉我的头发由于下面的问题:我下面的例子 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)
提供两个模板参数的正确方法?