C++分配器,特别是将构造函数参数传递给使用boost :: interprocess :: cached_adaptive_pool分配的对象

por*_*uod 7 c++ templates boost allocator boost-interprocess

这是一个令人尴尬的问题,但即使是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 ... ???
Run Code Online (Sandbox Code Playgroud)

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

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

我的头一整天都在模板中游泳,所以即使答案很明显,也会非常感激.

Unc*_*ens 1

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

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

就像是:

allocator_instance.construct(allocator_instance.allocate_one(), Test(30, true));
Run Code Online (Sandbox Code Playgroud)

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

a.construct(p, 30, true); //a C++0x allocator would allow this and call new (p) Test(30, true)
Run Code Online (Sandbox Code Playgroud)