【问题标题】:Does Boost Interprocess vector of struct containing strings require special allocator?包含字符串的结构的Boost Interprocess向量是否需要特殊的分配器?
【发布时间】:2018-05-03 22:42:02
【问题描述】:

我正在使用 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;
};

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    是的,是的。

    我没有时间从您的代码 sn-ps 中创建一个独立的示例,但这里有一些链接准确描述了您想要做什么:

    【讨论】:

    • 我担心的部分是将存储在这个共享向量中的类在我的代码库的其他地方声明——它们完全不知道 Boost Interprocess,所以我希望我不知道不必在定义它们的地方包含 Boost Interprocess 标头,然后创建分配器等。
    • 只要您可以使用分配器实例化这些类,就可以了。如果它们不支持自定义分配器(特别是有状态分配器),那么您将无法将它们存储在内存段中(当然,除非它们根本不分配)跨度>
    猜你喜欢
    • 2020-12-25
    • 2019-01-30
    • 2010-12-20
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    相关资源
    最近更新 更多