2

我已经盯着 Boost.Interprocess 文档看了好几个小时,但仍然无法弄清楚这一点。在文档中,他们有一个在共享内存中创建向量的示例,如下所示:

//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()as的原型

MyType *ptr = managed_memory_segment.construct<MyType>("Name") (par1, par2...);

但是当我尝试

MyVector *myvector = segment.construct<MyVector>("MyVector")(100, alloc_inst);

我得到编译错误。

我的问题是:

  1. 谁实际上是从对象的构造函数传递参数par1, par2segment.construct,例如vector?我的理解是正在传递模板分配器参数。那是对的吗?
  2. alloc_inst除了在共享内存中创建的对象的构造函数所要求的之外,我如何添加另一个参数?

除了简洁的 Boost 文档之外,几乎没有关于此的信息。

4

1 回答 1

3

我在 boost users 邮件列表上问了同样的问题,Steven Watanabe回答说问题很简单:std::vector 没有类型(大小,分配器)的构造函数。查看它的文档,我看到构造函数是

vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

所以正确的调用应该是

MyVector *myvector = segment.construct<MyVector>("MyVector")(100, 0, alloc_inst);

小学,亲爱的,华生,小学!

于 2010-03-13T15:35:02.600 回答