我想在共享內存中使用Boost進程庫創建一個unordered_map。這裏,是代碼,這是我想要使用(以從升壓進程間文件的例子):boost進程間unordered_map字符串
#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。然而,當我試圖訪問地圖,我需要使用像
persons->at(ShmemString("H", segment.get_allocator<char>())).print();
語法但是,我寧願用的std :: string,這會導致編譯錯誤做到這一點:
persons->at(std::string("H")).print();
是否有可能編寫上述語句,即使用std :: string訪問共享內存中分配的映射?
我發佈在boost-users郵件列表上。並且,從Boost.Interprocess作者那裏得到了一個答案,這是無法完成的。 – Lazylabs 2013-03-15 16:00:58