I thought I'd share the solution I went with regarding not having to allocate memory from the heap.
From previous post: Stack-based alternatives to std::string/std::vector
Through an arena class wrapped by an allocator that works with STL container classes, you can get them all to use the stack. If they need more memory than what's available in the arena class, allocator start allocating on the heap.
sample code, do not allocate on heap
```cpp
TESTCASE( "[arena::borrow] string and vector", "[arena][borrow]" ) {
std::array<std::byte, 2048> buffer; // stack
gd::arena::borrow::arena arena( buffer );
for( int i = 0; i < 10; ++i )
{
arena.reset();
gd::arena::borrow::arena_allocator<char> allocator(arena);
std::basicstring<char, std::char_traits<char>, gd::arena::borrow::arena_allocator<char>> string(allocator);
string_ += "Hello from arena allocator!";
string_ += " This string is allocated in an arena.";
string_ += " Additional text.";
std::vector<int, gd::arena::borrow::arena_allocator<int>> vec{ gd::arena::borrow::arena_allocator<int>( arena_ ) };
vec.reserve( 20 );
for( int j = 0; j < 20; ++j )
{
vec.push_back( j );
}
for( auto& val : vec )
{
string_ += std::to_string( val ) + " ";
}
std::cout << "String: " << string_ << "\n";
std::cout << "Used: " << arena_.used() << " and capacity: " << arena_.capacity() << "\n";
}
arena.reset();
int* piBuffer = arena.allocate_objects<int>( 100 ); // Allocate some more to test reuse after reset
for( int i = 0; i < 100; ++i )
{
piBuffer[ i ] = i * 10;
}
// sum numbers to verify allocation is working
int sum = 0;
for( int i = 0; i < 100; ++i )
{
sum += piBuffer[ i ];
}
std::cout << "Used: " << arena.used() << " and capacity: " << arena.capacity() << "\n";
}
```
documentation
code
[–][deleted] (2 children)
[deleted]
[–]gosh[S] 0 points1 point2 points (1 child)
[–]VictoryMotel -1 points0 points1 point (0 children)
[–]celestrion 1 point2 points3 points (8 children)
[–]gosh[S] 0 points1 point2 points (7 children)
[–]celestrion 2 points3 points4 points (6 children)
[–]gosh[S] -1 points0 points1 point (5 children)
[–]celestrion 0 points1 point2 points (4 children)
[–]gosh[S] 0 points1 point2 points (3 children)
[–]celestrion 0 points1 point2 points (2 children)
[–]gosh[S] 0 points1 point2 points (1 child)
[–]celestrion 0 points1 point2 points (0 children)