7

这是一个令人尴尬的问题,但即使是 boost.interprocess 提供的编写良好的文档也不足以让我弄清楚如何做到这一点。

我拥有的是一个cached_adaptive_pool分配器实例,我想用它来构造一个对象,传递构造函数参数:

struct Test {
  Test(float argument, bool flag);
  Test();
};

// Normal construction
Test obj(10, true);
// Normal dynamic allocation
Test* obj2 = new Test(20, false);

typedef managed_unique_ptr<
    Test, boost::interprocess::managed_shared_memory>::type unique_ptr;

// Dynamic allocation where allocator_instance == cached_adaptive_pool,
// using the default constructor
unique_ptr obj3 = allocator_instance.allocate_one()
// As above, but with the non-default constructor
unique_ptr obj4 = allocator_instance ... ???

这很可能是我在一般情况下如何使用分配器对象方面的失败。但无论如何,我看不到如何使用这个特定的分配器,通过cached_adaptive_pool中指定的接口将构造函数参数传递给我的对象。

cached_adaptive_pool有方法:void construct(const pointer & ptr, const_reference v)但我不明白这意味着什么,我找不到使用它的例子。

我的头整天都在模板中游泳,所以即使答案很明显,也将不胜感激。

4

2 回答 2

1

我想我总是可以使用放置新语法。这个想法是取消引用分配器返回的智能指针(在本例中为 offset_ptr),然后将原始地址传递给 new()。

unique_ptr obj = new(&(*allocator_instance.allocate_one())) Test(1,true)

这是这样做的惯用方式吗?在 boost 中还有很多其他地方提供了明确的支持以避免使用placement new,这让我不这么认为。无论如何,如果在不久的将来没有提供更好的答案,我会接受这个答案。

于 2010-04-07T22:02:33.063 回答
1

cached_adaptive_pool 有方法: void constructor(const pointer & ptr, const_reference v) 但我不明白这是什么意思,也找不到使用它的示例。

它应该遵循 的接口std::allocator,在这种情况下allocate()为您提供合适的未初始化内存块并construct()在给定指针上调用placement new。

就像是:

allocator_instance.construct(allocator_instance.allocate_one(), Test(30, true));

不过,我自己并没有使用过这些游泳池。在 C++0x 中,分配器应该能够调用任何构造函数,而不仅仅是复制构造函数,因此 boost 的分配器可能已经在一定程度上支持这一点。

a.construct(p, 30, true); //a C++0x allocator would allow this and call new (p) Test(30, true)
于 2010-04-07T22:09:00.510 回答