【问题标题】:How to pass parameters to manage_shared_memory.construct() in Boost.Interprocess如何在 Boost.Interprocess 中将参数传递给 manage_shared_memory.construct()
【发布时间】:2011-01-27 02:14:19
【问题描述】:

我已经盯着 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);

我收到编译错误。

我的问题是:

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

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

【问题讨论】:

    标签: c++ shared-memory boost-interprocess


    【解决方案1】:

    我在 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);
    

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

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2018-08-14
      • 2014-10-16
      • 2020-02-04
      • 2019-12-29
      • 1970-01-01
      • 2018-05-28
      • 2013-09-25
      • 1970-01-01
      相关资源
      最近更新 更多