1

As far as I know, when a vector runs out of space the allocator is used to create new space. However, I want to create a custom resize policy that will remove the bottom 25% of elements instead and maintain the same size all the time. This is to build a cache that has limited space.

Is there a method or default functor I can override to get the behavior I want?

Niall
  • 30,036
  • 10
  • 99
  • 142
andre
  • 155
  • 9
  • That's not the responsibility of allocators. Try Boost.CircularBuffer. – milleniumbug Jun 15 '16 at 14:48
  • You need to call destructors for these elements, and an allocator is too low-level to do it. You probably don't want a `std::vector` at all. Have a look at [`boost::circular_buffer`](http://www.boost.org/doc/libs/1_61_0/doc/html/circular_buffer.html). – Quentin Jun 15 '16 at 14:48
  • 2
    http://stackoverflow.com/questions/5559730/which-stl-c-container-to-use-for-a-fixed-size-list, http://stackoverflow.com/questions/9516711/efficient-circular-list, http://stackoverflow.com/questions/9743605/thread-safe-implementation-of-circular-buffer, http://stackoverflow.com/questions/19059336/c-threadsafe-ringbuffer-implementation – Cody Gray - on strike Jun 15 '16 at 14:52

1 Answers1

3

TL;DR, you are trying to use the wrong container.

The allocator is responsible for the allocation, deallocation etc. of the memory as required by the container. It is the responsibility of the container to implement the required semantics and it uses the allocators to assist it in doing so.

std::vector is probably not the best choice for the cache you describe, or at least not in its raw form.

You can look to boost (circular_buffer) as an alternative.

Given the vector you mention, you could also look to wrap that with the cache interface you desire, but changing the allocator is not the correct route. Changes to the allocator will leave the vector thinking there are valid objects in the "lower" 25% of the container, whilst the allocator has already removed them (or the memory to them).

Niall
  • 30,036
  • 10
  • 99
  • 142