c++ - 包含字符串的结构的 Boost Interprocess vector 是否需要特殊分配器?

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

我正在使用 Boost Interprocess 在共享内存中创建一个 interprocess::vector。我模板化了我的类,这样我就可以在内存中存储任何类型的对象:

using namespace boost::interprocess;

template<typename T>
struct MySharedData
{
    using ShmemAllocator = allocator<T, managed_shared_memory::segment_manager>;
    using MyVector = vector<T, ShmemAllocator>;

    MySharedData()
    {
        segment.reset(new managed_shared_memory(open_or_create, "memory", 10000));
        const ShmemAllocator alloc_inst(segment->get_segment_manager());
        vec = segment->find_or_construct<MyVector>("vector")(alloc_inst);
    }

    //...
    //...

    MyVector*                               vec{nullptr};
    std::unique_ptr<managed_shared_memory>  segment{nullptr};
}

我通过简单地调用添加了元素:

vec->push_back(element);

在测试期间,我使用 int 对我的类进行了模板化,效果很好。然而,当我后来使用我的复杂对象时,包括:

struct Complex
{
    std::string x;
    std::string y;
    double a;
    int b;
};

我在遍历 vector 并访问元素后不久遇到了段错误:

std::vector<T> read()

    // Mutex and condition variable stuff here

    std::vector<T> toReturn;

    for(auto& t : *vec)
    {
        toReturn.push_back(t);
    }

    return toReturn;
}

我正在阅读此页面:

https://www.boost.org/doc/libs/1_60_0/doc/html/interprocess/allocators_containers.html

它提到“容器的容器”要求元素类型有自己的分配器。

我的 Complex 结构是否也需要这个,因为字符串使我的 vector 成为容器的容器(字符),它会解释为什么我在迭代元素时遇到段错误吗?

最佳答案

Does my Complex struct require this too, because a string makes my vector a container of container (of chars) and would it explain why I was experiencing segmentation faults whilst iterating over the elements?

是的,是的。

我没有时间根据您的代码片段创建一个独立的示例,但这里有一些链接准确描述了您想要执行的操作:

关于c++ - 包含字符串的结构的 Boost Interprocess vector 是否需要特殊分配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164759/

相关文章:

c++ - 在另一个函数中 boost 读/写锁

c++ - 异步共享内存读/写

java - Java中如何从共享内存中读取信息?

python多处理共享内存数组不允许二维数组

c++ - 需要一些使用指针添加 C++ 数组的建议

c++ - 处理 tcp/udp 接收的最佳方式。

C++ 位图每像素位

c++ - 有没有一种方法可以在没有 while 循环的情况下在计算机之间传递数据? C++

c++ - 如何在 C++ 中显式调用异常抛出方法?

c++ - 将静态常量数据添加到已定义的结构中