我已经盯着Boost.Interprocess文档几个小时但仍然无法解决这个问题。在文档中,他们有an example在共享内存中创建一个向量,如下所示:
//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 vector<int, ShmemAllocator> MyVector;
int main(int argc, char *argv[])
{
//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 vector named "MyVector" in shared memory with argument alloc_inst
MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);
现在,我理解这一点。我遇到的问题是如何将第二个参数传递给segment.construct()
以指定元素的数量。进程间文档将construct()
的原型作为
MyType *ptr = managed_memory_segment.construct<MyType>("Name") (par1, par2...);
但是当我尝试
时MyVector *myvector = segment.construct<MyVector>("MyVector")(100, alloc_inst);
我收到编译错误。
我的问题是:
par1, par2
传递参数segment.construct
,对象的构造函数,例如vector
?我的理解是模板分配器参数正在传递。这是对的吗?alloc_inst
之外添加另一个参数? 除了简洁的Boost文档之外,其他信息非常少。
答案 0 :(得分:3)
我在boost用户邮件列表和Steven Watanabe replied上提出了同样的问题,问题很简单:std :: vector没有类型的构造函数(size,allocator)。看看它的文档,我看到构造函数是
vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
所以正确的电话应该是
MyVector *myvector = segment.construct<MyVector>("MyVector")(100, 0, alloc_inst);
小学,亲爱的,沃森,小学!