Puppy
Puppy

Reputation: 146968

Realloc- in Standard allocator

For the Standard allocator interface for use in, say, std::vector, is re-allocation supported? I have a rather specific use-case in which being able to realloc directly would be much more efficient than allocating, moving, and freeing.

Edit: Sorry- I have absolutely no intention of calling the actual realloc, I meant a function with those semantics. Effectively, I'm allocating off a stack in the background, and if I allocate more off the stack, then I can't free the memory underneath it, which is a total waste because there's no need to allocate again anyway as there's plenty of contiguous free space available. Thus, if I could be asked to reallocate in a single step, then I could avoid having to firstly, allocate some stuff and waste some memory, and secondly, move all the contents of the vector.

Upvotes: 18

Views: 2995

Answers (3)

mike jones
mike jones

Reputation: 659

You can put a bool flag in the structure you are saving in the std::vector to indicate it its logically deleted or not. To delete an element set this flag to true but don't physically delete it. To reallocate an element, look for an flag that's true, set it to false to show its not deleted and that use it.

Upvotes: 0

Jacob B
Jacob B

Reputation: 2015

I believe that realloc() is not part of the STL allocator interface. But realloc() is always a crap-shoot anyway, since you don't really know whether your OS will expand your allocation or move you to a new one. Actual performance is very OS-dependent. If you know you want to reallocate, you might as well just alloc a bigger chunk of memory in advance, which luckily the STL makes easy.

Do you have a use case where this would be undesirable?

Upvotes: 2

Related Questions