1

I am using Boost Interprocess to create an interprocess::vector in shared memory. I templated my class, so that I could store any type of object in the memory:

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};
}

and I added elements by simply calling:

vec->push_back(element);

During testing I templated my class using int, which worked fine. However, when I later used my complex object, consisting of:

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

I encountered segmentation faults shortly after iterating through the vector and accessing the elements:

std::vector<T> read()

    // Mutex and condition variable stuff here

    std::vector<T> toReturn;

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

    return toReturn;
}

I was reading this page:

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

and it mentions "containers of containers" require the element type to have their own allocator.

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?

intrigued_66
  • 16,082
  • 51
  • 118
  • 189

1 Answers1

0

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?

Yes, and yes.

I don't have time to create a self contained example out of your code snippets, but here are some links describing exactly what you want to do:

sehe
  • 374,641
  • 47
  • 450
  • 633
  • The part I'm worried about is the classes which will be stored in this shared vector are declared elsewhere in my code base- they are totally unaware of Boost Interprocess and so I'm hoping I don't have to go and include Boost Interprocess headers where they are defined, to then create the allocators etc. – intrigued_66 May 04 '18 at 00:39
  • As long as you can instantiate those classes with allocators, you are fine. If they don't support custom allocators (in particular, stateful allocators) then you _will not_ be able to store them in the memory segment (unless, of course, they do not allocate at all) – sehe May 04 '18 at 01:32