由于以下问题,我正在拉扯我的头发:我正在按照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
}
}
我的第一个问题:这种分配是否保证缓冲区节点分配在连续的内存位置,即当我尝试从m_start_ptr + n*sizeof(BufferNode)
我的Read()
方法中的地址访问第 n 个节点时它会起作用吗?如果没有,有什么更好的方法来保留节点,创建一个链表?
我的测试工具如下:
// 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)
提供两个模板参数的正确方法是什么?