如何使用boost :: allocate_shared指定分配器?

时间:2013-04-08 17:10:44

标签: c++ performance memory

我正在尝试使用allocate_shared来提高boost :: shared_ptr的性能。问题是我不确定我应该将什么样的分配器完全传递给boost :: allocate_shared。

我有以下内容:

struct MagicalData {...};

// My simple allocator example 
template <typename T>
class MyAlloc
{
 public:

typedef T                 value_type;
typedef value_type*       pointer;
typedef const value_type* const_pointer;
typedef value_type&       reference;
typedef const value_type& const_reference;
typedef std::size_t       size_type;
typedef std::ptrdiff_t    difference_type;

template<typename U>
struct rebind {
    typedef MyAlloc<U> other;
};  

pointer allocate(size_type n, const_pointer = 0) {
    void* p = std::malloc(n * sizeof(T));
    if (!p)
      throw std::bad_alloc();
    return static_cast<pointer>(p);
}   

void deallocate(pointer p, size_type) {
    std::free(p);
}   

size_type max_size() const { 
    return static_cast<size_type>(-1) / sizeof(value_type);
}   
};

MyAlloc alloc;

// Compilation error
boost::shared_ptr<MagicalData> magicalData 
       = boost::allocate_shared<MagicalData>(alloc, j);

我在这里遇到令人费解的编译错误:

/usr/include/boost-1_51/boost/smart_ptr/detail/shared_count.hpp:239:18: error: no matching function for call to ‘MyAlloc<boost::detail::sp_counted_impl_pda<MagicalData*, boost::detail::sp_ms_deleter<MagicalData>, MyAlloc<MagicalData> > >::MyAlloc(MyAlloc<MagicalData>&)'

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

看起来我错过了这个。来自wiki:分配器应该是可复制构造的。类型为T的对象的分配器可以从U类型的对象的分配器构造。如果分配器A分配一个内存区域R,那么R只能由一个比较等于A的分配器释放。[11 ]

相关问题