Following up a similar question some months ago <[combination of monotonic buffer and unsynchronized memory pool]/questions/77271609/c17-combination-of-monotonic-buffer-and-unsynchronized-memory-pool>, I am trying to combine monotonic buffer and unsynchronized pool resource to efficiently allocate memory without got to heap for memory allocation.
#include <iostream>
#include <memory_resource>
#include <vector>
class A{
char array[64];
};
typename std::aligned_storage<32000>::type storage;
thread_local std::pmr::monotonic_buffer_resource bufferPool{&storage,sizeof(storage),std::pmr::null_memory_resource()};
std::pmr::unsynchronized_pool_resource pool{{},&bufferPool};
int main()
{
for(int i =0; i < 10000;++i){
std::pmr::vector<A> vec (&pool);
vec.reserve(1000);
for(int j =0; j < 1000;++j){
vec.emplace_back();
}
}
}
Based on the previous answer the expectation the memory block to return in pool and reuse for next allocation. But this does not happen. In next allocations go again to monotonic buffer which behaves monotonically and after some iterations memory runs out
What am I missing?
And why the below example works and reuse the same memory in each iteration?
#include <iostream>
#include <memory_resource>
int main() {
char buffer[1024];
std::pmr::monotonic_buffer_resource monotonicResource(buffer, sizeof(buffer));
// Use an unsynchronized_pool_resource on top of the monotonic_buffer_resource
std::pmr::unsynchronized_pool_resource poolResource(&monotonicResource);
// Allocate and deallocate memory using the unsynchronized_pool_resource
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration " << i << ":n";
// Allocate memory
void* ptr = poolResource.allocate(200); // request 200 bytes from the pool
std::cout << "Allocated at: " << ptr << "n";
// Deallocate memory (returning it to the pool! Not the monotonic resource)
poolResource.deallocate(ptr, 200);
std::cout << "Deallocated.nn";
}
return 0;
}
What is the difference between them?