user1289 user1289 - 2 months ago 7
C++ Question

Is it guaranteed that std::vector each allocated memory with allocate function, will also deallocate at once, with single deallocate call?

I'm writing custom allocator for std::vector, and want to know how std::vector uses specified allocator? May it allocate memory for 5 objects, and then deallocate memory partially, for example at first 2 element, then 3 elements... (I don't see any reason not to do so).

Is there anything mentioned about it in standard? I couldn't find anything.

Answer

Is it guaranteed that std::vector each allocated memory with allocate function, will also deallocate at once, with single deallocate call?

Yes. The prototype of std::allocator::deallocate is

void deallocate( pointer p, size_type n );

May it allocate memory for 5 objects, and then deallocate memory partially, for example at first 2 element, then 3 elements... (I don't see any reason not to do so).

But n cannot be different from what was passed earlier to the matching allocate function, as explained in the spec.:

Deallocates the storage referenced by the pointer p, which must be a pointer obtained by an earlier call to allocate(). The argument n must be equal to the first argument of the call to allocate() that originally produced p.

Basically, the arguments to deallocate are

  1. whatever was returned by allocate
  2. the corresponding n that was passed for getting it
Comments