Polymorphism-free memory resource class with custom allocator and deallocator functions.
More...
Polymorphism-free memory resource class with custom allocator and deallocator functions.
This is used as the "back-end" for Allocator objects. The allocator and deallocator functions are member objects of type std::function, specified as constructor arguments.
Example: a class that needs to allocate memory, and should have a way to use a specified PSI key, can be implemented as follows:
- For each type the class needs to allocate, it has one member object of type Allocator. The constructor takes a Memory_resource parameter, which defaults to a default-constructed Memory_resource. The constructor passes the Memory_resource to the Allocator constructors. The class calls the Allocator member functions for its memory management.
- API clients that don't need a PSI key don't need to pass a Memory_resource to the constructor; they use the default value for the parameter. API clients that need a PSI key, pass a Memory_resource object where the allocate/deallocate functions are PSI-enabled. Such a Memory_resource object can be obtained from the factory function
psi_memory_resource
in sql/psi_memory_resource.h.
Notes on design choices:
We avoid using polymorphism to configure the behavior of the allocate/deallocate member functions. Classes that use polymorphic memory resources would have to take a reference or pointer to the memory resource as argument, so either the class can't own the memory resource or it has to be dynamically allocated. If the class can't own the memory resource, it complicates the usage since the caller has to ensure the Memory_resource outlives the class that uses it. If the Memory_resource has to be allocated dynamically, that allocation cannot use a custom Memory_resource, which may defeat the purpose of using custom Memory_resources to track all allocations.
We also avoid static polymorphism, since every user of a statically polymorphic Memory_resource would have to be a template, which has two problems: first, two classes with the same behavior but different allocation strategies would be different types. Second, any class that allocates memory and has a requirement that the API client can configure the Memory_resource, has to be templated and therefore be defined in a header.
With the current solution, the caller just creates a Memory_resource object and passes it to the allocator.