This is an introduction to the custom memory management strategies you should be using to write "correct" code.

Introducing the custom allocator

The framework ships with a custom allocator (UImGui::Allocator) that should be used by your application. It contains all the functions a standard C++ custom allocator should have.

This is needed to enable us to have plugins on Windows. It's good practice to use the custom allocator, however, it should be compatible with the normal standard allocator in most cases if you don't want to support plugins on Windows.

Caution

Make sure that you're using the correct wrappers on top of the regular standard library types. Standard library containers should not be used as is. More info can be found here.

The Allocator<T> class

UImGui::Allocator<T> is an STL-compatible allocator template. It defines value_type = T and provides static allocate(n) and deallocate(ptr, n) functions, which internally route through UImGui_Allocator_allocate and UImGui_Allocator_deallocate. All instances of Allocator<T> and Allocator<T1> compare equal, which makes the allocator stateless and trivially copyable between standard library containers.

This allocator is what powers the TVector, TMap, TUnorderedMap, TFString and other framework type wrappers defined in Core/Types.hpp. A full list of these types can be found here.

The framework also overrides the global operator new and operator delete to go through the same allocator. This means that any standard C++ new/delete allocation in framework, application and plugin code consistently goes through the same allocator implementation.

The AllocatorFuncs struct

The framework keeps a small struct of allocator function pointers that gets shared with plugins via the PluginContext. The struct looks like this:

class AllocatorFuncs
{
public:
    void*(*allocate)(size_t);
    void(*deallocate)(void*);

    static AllocatorFuncs& get(AllocatorFuncs* parent = nullptr) noexcept;
};

AllocatorFuncs::get() returns the global allocator function table. When parent is passed in (used by plugins via Utility::loadContext), the plugin's allocator table is replaced with the host's, so all heap allocations done by the plugin go through the host's allocator. This is what makes cross-DLL delete of a new-allocated object safe on Windows.

C API

In the C API, you also have access to the following functions as replacements for malloc and free:

  1. UImGui_Allocator_allocate
  2. UImGui_Allocator_deallocate

C API memory management

The C API provides you with 2 ways of managing your memory:

  1. Auto-deallocated - for objects that have relatively the same lifetime as the application
  2. Manually managed

In many interfaces, you can decide which deallocation strategy you want to use for a handle by toggling the bManualDeallocation boolean argument, which should be the last argument of the function that returns the handle. You can then call the respective free function for it.