代码之家  ›  专栏  ›  技术社区  ›  recipriversexclusion

如何在boost.interprocess中传递参数来管理共享内存.construct()

  •  2
  • recipriversexclusion  · 技术社区  · 16 年前

    我已经盯着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. 实际通过参数的人 par1, par2 segment.construct ,对象的构造函数,例如。 vector ?我的理解是正在传递模板分配器参数。是这样吗?
    2. 除了 alloc_inst 在共享内存中创建的对象的构造函数所需要的?

    除了简短的boost文档之外,几乎没有其他信息。

    1 回复  |  直到 16 年前
        1
  •  3
  •   recipriversexclusion    16 年前

    我在boost用户邮件列表和steven watanabe上问了同样的问题 replied 问题很简单:STD::vector没有类型的构造函数(大小,分配器)。看一下它的文档,我发现构造函数是

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

    所以正确的做法应该是

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

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