Boost logo

Boost :

Subject: [boost] stack-allocated STL-containers
From: Stefan Strasser (strasser_at_[hidden])
Date: 2009-08-13 15:52:33

I recently ran into the problem that a local container on the stack, which was
likely to be very small, but its size was still not known at compile-time,
consumed a considerable amount of runtime because of allocation/deallocation.

void do(istream &i){
        vector<int> vec; vec.reserve(20);

                int tmp; i >> tmp;

so I wrote an allocator that I think is generally useful and could be added
e.g. to Boost.Array:

void do(int n){
        int buffer[20];
        stack_allocator<int,20> alloc(buffer);
        vector<int,stack_allocator<int,20> > vec(alloc);

                int tmp; i >> tmp;

the vector operates on the stack as long as there is enough space, and moves
to the heap afterwards.
in most cases there is no dynamic allocation.

here's the source:

it uses the simple_seq_fit allocation algorithm described here:

Boost list run by bdawes at, gregod at, cpdaniel at, john at