我想在共享内存中保留大量的(经常重复的)字符串,所以我使用了Boost的轻量级和进程间basic_string功能。为了确保字符串实际存储在共享内存中,我需要在flyweight使用的hashed_factory中提供一个自定义分配器。使用Boost轻量级共享内存
但是,当我将自定义分配器指定为hashed_factory时,无法编译(g ++ 4.2.1)...可能是因为它需要额外的参数来指定段管理器。什么是语法来得到这个工作,或者有更好的方法来做到这一点?
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/flyweight.hpp>
#include <boost/flyweight/no_tracking.hpp>
#include <boost/flyweight/hashed_factory.hpp>
using namespace boost::flyweights;
using namespace boost::container;
using namespace boost::interprocess;
typedef boost::interprocess::allocator<boost::mpl::_1, boost::interprocess::managed_mapped_file::segment_manager> ShmFactoryEntryAllocator;
typedef boost::interprocess::allocator<char, boost::interprocess::managed_mapped_file::segment_manager> ShmAllocatorChar;
typedef boost::interprocess::basic_string<char, std::char_traits<char>, ShmAllocatorChar> ShmString;
// TODO: using ShmFactoryEntryAllocator does not work
typedef boost::flyweights::hashed_factory<boost::hash<ShmString>, std::equal_to<ShmString>, ShmFactoryEntryAllocator> ShmStringHashedFactory;
//typedef boost::flyweights::hashed_factory<boost::hash<ShmString>, std::equal_to<ShmString>, std::allocator<boost::mpl::_1> > ShmStringHashedFactory;
// TODO: need to be able to use a hashed_factory with our custom allocator.
typedef boost::flyweights::flyweight<ShmString, ShmStringHashedFactory> ShmFlyweightString;
//typedef boost::flyweights::flyweight<ShmString> ShmFlyweightString;
int main(int argc, char** argv)
{
managed_mapped_file *segment = new managed_mapped_file(create_only, "memory.dat", 409600);
ShmFactoryEntryAllocator factoryEntryAllocator(segment->get_segment_manager());
// create a normal string in shared-memory.
ShmString *ps1 = segment->construct<ShmString>("s1")("some shm normal string", factoryEntryAllocator);
// create a flyweight string in shared memory.
ShmFlyweightString *ps2 = segment->construct<ShmFlyweightString>(anonymous_instance)("some shm flyweight string", factoryEntryAllocator);
return 0;
}
的TODO注释后的线是有问题的线路,加上注释的版本是说工作,但没有使用正确的分配器的人。
我认为这样越来越接近了,但我仍然无法完成编译。事实证明,MyShmAllocator构造函数实际上不应该取消引用指针。但是,在将ShmStringHashedFactory切换为使用MyShmAllocator后,它仍然不太高兴...... https://gist.github.com/bovine/5863647 – bovine
事实证明,您的答案是正确的,但还有更多需要一个完整的解决方案,例如拥有知道如何存储共享内存和锁定策略的持有者类。我的同事在Boost邮件列表中提出了同样的问题,并从JoaquínMLópezMuñoz那里得到了非常全面的答案:http://permalink.gmane.org/gmane.comp.lib.boost.devel/242512 – bovine