5

I want to have a std::vector of objects, with the objects allocated using boost::pool. Is something like this correct:

class MyClass
{
private:
    double data;
public:
    MyClass(double d) : data(d) {  }
};

int main()
{
    std::vector<MyClass, boost::fast_pool_allocator<MyClass> > vect;
    vect.push_back(4.5);
    vect.push_back(9.8); //Are these being stored in a pool now?

    return 0;
}

This code works, but I'm not entirely sure why. I am quite new to the concept of allocators, but if I understand correctly this is telling std::vector to use a pool instead of the default allocator, so any elements created in the vector will be created from a pool.

What I'm not exactly sure of, is:

Where is the pool?

And how would I access the pool directly (to free memory for example)?

Does fast_pool_allocator contain a pool, or do I need to create the pool separately and somehow tell the allocator to use it.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Verwirrt
  • 403
  • 2
  • 13
  • 1
    You might want to read e.g. [this `std::vector` reference](http://en.cppreference.com/w/cpp/container/vector). I'm sure you can find a suitable function to get the allocator. You might also want to check out the [`std::vector` constructors](http://en.cppreference.com/w/cpp/container/vector/vector). – Some programmer dude Jul 22 '14 at 16:03
  • 1
    The [boost reference](http://www.boost.org/doc/libs/1_55_0/libs/pool/doc/html/boost/fast_pool_allocator.html) says to use `boost::pool_allocator` with `std::vector`. – Khouri Giordano Jul 22 '14 at 16:09

2 Answers2

3

In the case of boost::fast_pool_allocator the pool is a singleton owned by the allocator implementation. So you do not need to create anything separately.

You can access the allocator via get_allocator function of std::vector, or you can use static functions in boost::fast_pool_allocator.

sehe
  • 374,641
  • 47
  • 450
  • 633
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
3

Looking at the boost reference, there is a singleton instance of the allocator that is used by all. You can use it to allocate memory as well as free it, just by creating a local boost::fast_pool_allocator or boost::pool_allocator object.

Khouri Giordano
  • 1,426
  • 15
  • 17