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?