Orxonox  0.0.5 Codename: Arcturus
Classes | Namespaces
SmallObjectAllocator.h File Reference

Declaration of SmallObjectAllocator. More...

#include "UtilPrereqs.h"
#include <vector>
#include <cstdio>

Go to the source code of this file.

Classes

class  orxonox::SmallObjectAllocator
 This class is used to allocate and free small objects (usually not polymorphic). More...
 
struct  orxonox::SmallObjectAllocator::Chunk
 The memory chunk is at the same time an element of a single linked list. More...
 

Namespaces

 orxonox
 Die Wagnis Klasse hat die folgenden Aufgaben:
 

Detailed Description

Declaration of SmallObjectAllocator.

The default implementations of new and delete are designed to work with objects of arbitrary size. They are thus not optimal for small objects. SmallObjectAllocator allocates a large memory block and divides it into small chunks. These chunks are returned by the function alloc() and can be used to create a new object using the placement new operator. Instead of delete, the function free() is used to give the memory back to SmallObjectAllocator.

Example:

SmallObjectAllocator allocator(sizeof(MySmallObject)); // Create an allocator. The size of the memory chunks must equal the size of the desired class
void* chunk = allocator.alloc(); // Allocate a memory chunk
MySmallObject* object = new (chunk) MySmallObject(); // Call the placement new operator
object->someFunction(); // Do something with the object
object->~MySmallObject(); // Call the destructor
allocator.free(object); // Free the allocated memory

Important: You have to call the destructor of the object manually, because this is not automatically done by the allocator nor free().

Note
The destructor can be ignored if it is empty or not implemented. This saves another amount of time.
Remarks
For a distributed usage of SmallObjectAllocator it may be a good idea to create a static function that returns an instance to it. The allocator then works like a singleton and can be accesses from everywhere.