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.

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

        while(...){
                int tmp; i >> tmp;
                vec.push_back(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);
        vec.reserve(alloc.max_stack_size());

        while(...){
                int tmp; i >> tmp;
                vec.push_back(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:
http://www.boostpro.com/vault/index.php?action=downloadfile&filename=stack_allocator.hpp&directory=array&

it uses the simple_seq_fit allocation algorithm described here:
http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/allocators_containers.html#interprocess.allocators_containers.memory_algorithms


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk