我拉我的頭髮由於下面的問題:我下面Boost.Interprocess中文檔中給出the example實例,我在共享內存中寫了一個固定大小的環形緩衝區緩存類。我的課的骨架構造是:實例化類的共享內存自定義分配器
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)
訪問的第n個節點在我的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)
是提供兩個模板參數的正確方法嗎?
感謝您的回覆。我怎樣才能使用提供的分配器創建一個BufferNode對象的數組?我必須承認,我對boost.interprocess有點不穩定,例子很少。 – recipriversexclusion 2010-03-12 23:33:55
或者,創建一個向量來緩衝區內存儲BufferNode會更好嗎? – recipriversexclusion 2010-03-12 23:35:28
我會說使用'雙端隊列'(或至少是一個矢量''),並有'SharedMemoryBuffer'這個隱藏實現細節。容器的最終選擇取決於您的需求。 –
dirkgently
2010-03-12 23:57:29