Zen C++ Libraries
Zero-dependency re-usable components for C++
Loading...
Searching...
No Matches
alloc.hpp File Reference

Generic tools and utilities for using and defining allocators. More...

#include <concepts>
#include <new>
#include <utility>
#include "zen/config.hpp"

Go to the source code of this file.

Concepts

concept  DynamicAllocator

Typedefs

using destroy_fn = void (*)(void *)

Functions

template<typename R, DynamicAllocator Alloc, typename ... Ts>
R * construct (Alloc &allocator, Ts &&...args)

Detailed Description

Generic tools and utilities for using and defining allocators.

Unless writing a custom allocator, the most essential declaration in this header file is zen::construct. It allows you to construct any object inside the allocator of choice.

#include <iostream>
#include "zen/alloc.hpp"
int main() {
zen::bump_ptr_pool p;
int* one_in_pool = zen::construct<int>(p, 42);
std::cerr << "42 == " << *one_in_pool << "\n";
}
Generic tools and utilities for using and defining allocators.
Implementation of a bump-pointer allocator.

Typedef Documentation

◆ destroy_fn

using destroy_fn = void (*)(void *)

The signature of a function that is called whenever an object inside an allocator is going to be destroyed.

The function accepts a single void* parameter that contains a reference to the memory of the object that is being destroyed.

#include <iostream>
#include "zen/alloc.hpp"
struct Foo {
~Foo() {
std::cerr << "Foo is being destroyed!\n";
}
}
int main() {
zen::bump_ptr_pool allocator;
auto ptr = allocator.allocate(
sizeof(Foo),
alignof(Foo),
[](void* ptr) { static_cast<Foo*>(ptr)->~Foo(); }
);
auto foo = std::launder(reinterpret_cast<Foo*>(ptr));
// Foo's destructor will run at the end of the program
}
See also
construct for automatically constructing objects using an allocator

Function Documentation

◆ construct()

template<typename R, DynamicAllocator Alloc, typename ... Ts>
R * construct ( Alloc & allocator,
Ts &&... args )

Construct an object inside the memory provided by the given allocator.

#include <iostream>
#include "zen/alloc.hpp"
struct A { };
struct B : public A {
bool b;
B(bool b): A(), b(b) {}
};
struct C : public A {
int c;
C(int c): A(), c(c) {}
};
int main() {
zen::bump_ptr_pool p;
C* ptr = zen::construct<C>(p, 2);
if (!ptr) {
std::cerr << "out of memory!\n";
return 1;
}
std::cerr << "c = " << ptr->c << "\n";
}
See also
bump_ptr_pool for a simple allocator for dynamic objects
growing_bump_ptr_pool for an allocator that grows in size when out of memory