使用Boost flyweight和共享内存

时间:2013-06-21 17:17:24

标签: boost stdstring boost-interprocess boost-flyweight

我想在共享内存中保留大量(经常重复的)字符串,因此我使用Boost的flyweight和interprocess basic_string功能。为了确保字符串实际存储在共享内存中,我需要在flyweight使用的hashed_factory中提供自定义分配器。

但是,当我将自定义分配器指定为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注释之后的行是有问题的行,注释版本是有效的但不使用正确的分配器。

1 个答案:

答案 0 :(得分:0)

看起来您对所需构造函数参数的问题是正确的。 hashed_factory docs说:

  

hashed_factory_class所基于的内部哈希容器   使用Hash,Pred和类型的默认初始化对象构造   分配器。

我想知道你是否可以通过创建具有默认构造函数的共享内存分配器的子类来解决这个问题,并将段管理器传递给基类构造函数。例如,像这样:

class MyShmAllocator : public ShmFactoryEntryAllocator {
public:
  static boost::interprocess::managed_mapped_file::segment_manager *segmentManager;

  MyShmAllocator()
  : ShmFactoryEntryAllocator(*segmentManager) {
  }
};

在调用构造函数之前,您需要分配一个“当前”MyShmAllocator :: segmentManager。这有点难看,但我认为它应该有用。