Sivaram
Sivaram

Reputation: 155

Hinnant's short_alloc only on stack

I am trying to use Hinnant's short_alloc for allocating vectors on stack, I am trying to remove the heap allocation completely. Now comes the problem where the developer uses push_back beyond the vector size. I am thinking of overriding the push_back function such that it checks if the capacity is reached, if yes then it will assert the error. As it is understood that STL functions are not meant to be overridden, What will be the better approach to achieve.

Upvotes: 0

Views: 172

Answers (2)

JVApen
JVApen

Reputation: 11317

I used to be a pro on this allocator, however, it does require you to correctly deal with the arena.

As the vector with the allocator is a separate type from the regular vector, it doesn't play nice with existing APIs. Instead, I've recently switched to boost for the same behavior with less overhead:

  • small_vector: similar to the allocator
  • static_vector: only the stack part

Both containers contain the arena in the class itself and have decent support for copy and move.

Upvotes: 1

Brandon
Brandon

Reputation: 23485

First, you don't need to inherit anything to override anything. An allocator is allowed to throw an exception in the allocate function. After all, it uses ::operator new which will throw std::bad_alloc if it can't allocate memory. On my system it does: __throw_length_error("allocator<T>::allocate(size_t n) 'n' exceeds maximum supported size") as well..

So inside your allocate function, do:

throw std::bad_alloc();

Still.. I'm unclear as to why one wants a stack allocated std::vector when there are arrays.. But that's not my business.

Upvotes: 2

Related Questions