简体   繁体   中英

How should a C++ allocator handle its allocated memory when it is destroyed/copied/moved?

I am currently writing an allocator that should be usable by C++ standard data structures, ie, it implements the Allocator concept.

The allocator is quite simple: It allocates chunks of x objects and always hands out the next object if the current chunk is not full, otherwise it allocates a new chunk.

Now my question is: How to handle these chunks when the allocator is destroyed/copied/moved? The allocator concept says nothing about what must happen in these cases.

Here are my thoughts:

  • Destruction: The allocator may destroy all its chunks. But then, no object that uses any of the allocated objects may outlive the allocator.
  • Copying: The most straightforward idea would be to copy the chunks. But on second thought, this makes no sense: Nobody knows the address of the objects in the copied chunks, so they are just copied without any benefit. Maybe a copied allocator should start with an empty list of chunks.
  • Moving: The chunks should be moved to the new allocator. The old one should be left with an empty list of chunks.

Are my assumptions correct? If not, then why and where is this defined?

Allocators usually are lightweight objects that can be copied around and destroyed, eg in the standard container classes. Therefore they should not do the heavy memory management themselves but relay it to some more permanent memory manager object. If you do that, the lifetime of the memory chunks does not depend on the allocator lifetimes but on the lifetime of the memory manager object. The lifetime thoughts therefore have to be applied to both types of objects:

Allocator (short lifetime):

  • Copying/Moving: copy the reference to the memory manager.
  • Destruction: either does nothing (external lifetime management of the memory manager) or possibly destroys the memory manager, eg each allocator has a shared_ptr to the memory manager

Memory manager (long lifetime):

  • Copying should be forbidden, it makes no sense to duplicate the manager and its managed storage
  • Moving could be allowed, but does not make much sense. The memory manager could evene be a singleton-like class, ie one fixed instance that does not need to be moved around.
  • Destruction should involve the destruction of the managed memory, since no other object knows how to deallocate the managed storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM