包含字符串的结构的 Boost 进程间向量是否需要特殊的分配器?

Does Boost Interprocess vector of struct containing strings require special allocator?

本文关键字:分配器 是否 向量 结构 字符串 Boost 进程 包含      更新时间:2023-10-16

我正在使用 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 结构也需要这个吗,因为字符串使我的向量成为容器(字符(的容器,它能解释为什么我在迭代元素时遇到分段错误吗?

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

是的,是的。

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

  • 标准::unordered_map 与 boost::共享内存中的进程间分配器 - 缺点?
  • 提升进程间:在循环访问从结构引用对象的映射时删除字符串变量
相关文章: