首页 文章

包含字符串的struct的Boost Interprocess向量是否需要特殊的分配器?

提问于
浏览
1

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

并且它提到“容器容器”要求元素类型具有自己的分配器 .

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

1 回答

相关问题