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

标签 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 ... ???

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

cached_adaptive_pool 有方法:void construct(const pointer & ptr, const_reference v) 但我不明白那是什么意思,我找不到使用的例子

我一整天都在模板中游弋,所以即使答案很明显,也请伸出援助之手,我们将不胜感激。

最佳答案

cached_adaptive_pool has the method: void construct(const pointer & ptr, const_reference v) but I don't understand what that means and I can't find examples using it.

它应该遵循 std::allocator 的接口(interface),在这种情况下,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)

关于C++ 分配器,特别是将构造函数参数传递给使用 boost::interprocess::cached_adaptive_pool 分配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2595920/

相关文章:

c++ - 模板类无法正确构建

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

c++ - 实现嵌套在模板类中的类的成员函数

c++ - 使用 "cin"对象的问题

c++ - "The application has failed to start because cxcore210.dll was not found"。为什么会这样?

c++ - 释放内存映射内存

c++ - 最低共同祖先( boost 图)

c++ - 如何惯用地将 `` char *`` 转换为 `` double *``

c++ - fatal error :iostream:Code::Blocks 中没有这样的文件或目录

c++ - 在不更改成员范围的情况下有条件地启用静态成员