【问题标题】:C++ allocators, specifically passing constructor arguments to objects allocated with boost::interprocess::cached_adaptive_poolC++ 分配器,特别是将构造函数参数传递给使用 boost::interprocess::cached_adaptive_pool 分配的对象
【发布时间】:2011-02-05 11:00:00
【问题描述】:

这是一个令人尴尬的问题,但即使是 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 &amp; ptr, const_reference v),但我不明白这是什么意思,也找不到使用它的示例。

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

【问题讨论】:

    标签: c++ templates boost allocator boost-interprocess


    【解决方案1】:

    cached_adaptive_pool 有以下方法: 无效构造(常量指针和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)
    

    【讨论】:

    • 谢谢。第一种形式是我期待的那种答案,但是太困惑和疲倦而无法意识到自己。第二种形式 a.construct(p, 30, true) 似乎不被这个特定的 boost 分配器支持。够烦人的,既然cached_adaptive_pool.construct() 返回void,我就得写allocator_t::pointer obj = allocator.allocate_one(); allocator.construct(obj, Test(30, true))?我不确定哪个更糟,对一个简单的操作使用两个语句,或者直接使用一个看起来有点奇怪的放置 new。
    • 你可以把它做成一个单独的函数。
    【解决方案2】:

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

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

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

    【讨论】:

    • &amp;*ptr 序列的用途是什么?
    • 当我测试它时,new 只会接受一个原始指针,而不是这些分配器返回的 offset_ptr。
    猜你喜欢
    • 1970-01-01
    • 2012-07-09
    • 2013-11-05
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2011-11-28
    相关资源
    最近更新 更多