c++ - 提升进程间 unordered_map 字符串

标签 c++ unordered-map allocator boost-interprocess

我正在尝试使用 Boost Interprocess 库在共享内存中创建一个 unordered_map。这是我尝试使用的代码(以 Boost Interprocess 文档中的示例为例):

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>
#include <string>
#include <boost/interprocess/containers/string.hpp>

namespace bipc = boost::interprocess;

typedef bipc::allocator<char, bipc::managed_shared_memory::segment_manager> CharAllocator;
typedef bipc::basic_string<char, std::char_traits<char>, CharAllocator> ShmemString;


struct Person
{
  int age;
  ShmemString name;
  double salary;

  Person(int i,
     double sal,
     const char* s,
     const char_allocator& a)
    : age(i),
      name(s, a),
      salary(sal)
    {
    }
  void print() {}
}

typedef ShmemString KeyType;
typedef Person MappedType;

typedef std::pair< KeyType, MappedType > MapPersonType;


typedef bipc::allocator< MapPersonType,
                     bipc::managed_shared_memory::segment_manager >
ShMemAllocator;

typedef boost::unordered_map< KeyType,
                          MappedType,
                          boost::hash<KeyType>,
                          std::equal_to<KeyType>,
                          ShMemAllocator >
PersonMap;

这就是我在主程序中尝试做的事情:

int main() 
{
bipc::managed_shared_memory segment(bipc::create_only, "MySharedMemory", 65536);

PersonMap *persons = segment.construct<PersonMap>("MyHashMap")
    ( 3, boost::hash<ShmemString>(), std::equal_to<ShmemString>()
        , segment.get_allocator<MapPersonType>());

char_allocator alloc(segment.get_allocator<char>());

Person p1(20, 10000, "ABC", alloc);
persons->insert(MapPersonType(ShmemString("Person1", alloc), p1));
}

使用上面的代码,我可以在共享内存中创建一个 unordered_map。但是,当我尝试访问 map 时,我需要使用类似

的语法
persons->at(ShmemString("H", segment.get_allocator<char>())).print();

但是,我更愿意使用 std::string 来执行此操作,这会导致编译错误:

persons->at(std::string("H")).print();

是否可以编写上述语句,即使用 std::string 访问共享内存中分配的映射?

最佳答案

我发布了 this在 boost-users 邮件列表上。并且,从 Boost.Interprocess 的作者那里得到了一个答案,这是不能做到的。

关于c++ - 提升进程间 unordered_map 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15321744/

相关文章:

c++ - 1 智能感知 : no suitable constructor exists to convert from "bool" to "std::basic_string<char, std::char_traits<char>, std::allocator<char>>"

c++ - 节点句柄与 std::unique_ptr

c++ - 旧的 allocator::construct 和新的 allocator::construct 以及显式构造函数之间有什么区别?

c++ - 是否有标准的memory_resource分配器适配器/包装器?

C++ 模板 : cannot call my function from main. cpp

c++ - 抽象类型作为类成员变量的问题

c++ - 使用 vpaths 时需要两次 "make"

c++ - std::ofstream 的无序映射

c++ - 使用 C++11 中的 unordered_map 需要哪个 gcc 版本?

c++ - static_allocator 从 std::vector 生成 static_vector